Lists are one of the data structures in Python. It is considered an important data structure in Python.

Examples

A list of integers:

numbers = [1,2,3]

You can have a list with different data types:

list_of_items = ["Hello", 100, "World", False]

We can also search a list for an item by using the in operator:

print("World" in list_of_items) # True

We can also access elements in a list by using the index number:

list_of_items[1] # 100

We can also use index() to access elements in a list:

list_of_items.index(1) # 100

The end of a list can be searched in the following manner:

list_of_items[-1]

Part of a list can be extracted by slicing:

print(list_of_items[1:3]) # [100, 'World']
print(list_of_items[1:]) # [100, 'World', False]

We can use the append() method to add on elements to a list:

list_of_items.append([200,400]) # ["Hello", 100, "World", False, [200, 400]]

OR

We can use the extend() method also:

list_of_items.extend([500,600]) # ["Hello", 100, "World", False, [200, 400], 500, 600]

NOTE: append() and extend() both take one argument that is why we have to place the items we wish to append in between square brackets. The difference between them is that append will append what is in between the round brackets as is as we see in the example above, while extend will only place what is in between the square brackets.

We can also remove items from a list using remove():

list_of_items.remove([200,400]) # ["Hello", 100, "World", False, 500, 600]