The List¶
What’s a list¶
One of the most fundamental objects in python is the list. A list simply holds multiple objects, these can be of any type. A list can be generated in two ways:
# 1) with the [ ]
In [1]: my_list = [1, 2, 'some value', True]
In [2]: my_list
Out[2]: [1, 2, 'some value', True]
# 2) by converting some other object (an iterable) to a list with the list function
In [3]: my_other_list = list((1, 2, 3, 4, 5)) # this uses a tuple, which will be discussed later
In [4]: my_other_list
Out[4]: [1, 2, 3, 4, 5]
# a list can even hold other lists (nesting)
In [5]: my_nested_list = [[1, 2], [3, 4], [5, 6]]
In [6]: my_nested_list
Out[6]: [[1, 2], [3, 4], [5, 6]]
length, indexing, and slicing¶
You’ll notice in the example above that we mentioned an iterable. While it’s not strictly the definition you can think of an iterable as any sort of object that is a container for multiple objects. The number of objects in an iterable like a list is also known as the length of the list. Unsurprisingly there is a python function to get the length of an iterable like a list called len()
In [7]: my_list
Out[7]: [1, 2, 'some value', True]
In [8]: len(my_list) # using the lists defined above