Lists

lists

Lists

Video Transcript

In this section, we're going to learn about lists. A list in Python looks exactly like it sounds: a list of values separated by commas and contained inside a pair of square brackets. For example, [1, 2, 3, 4] would be a list, or ["a", "b", "c"], or even [1, "b", 2, "d"].
To create a list in Python, we use a pair of square brackets. If we leave them empty, Python will create an empty list, and if we include values inside, Python will create a list with those values in it:
x = []
print(x)
# []

x = ["a", "b", "c"]
print(x)
# ["a", "b", "c"]
To add an element to a list, we use the .append() method. This method takes a single argument and adds it to the end of the list:
x = ["a", "b", "c"]
x.append("d")
print(x)
# ["a", "b", "c", "d"]
To remove elements from a list, we have two options. If we want to remove a specific value, we use the .remove() method:
x = ["a", "b", "c"]
x.remove("b")
print(x)
# ["a", "c"]
If we want to remove an element at a specific position, we use the del keyword along with the position of the element. In Python, positions start from 0 instead of 1:
x = ["a", "b", "c"]
del x[0]
print(x)
# ["b", "c"]
Last section Next section