Summary: List concepts and basic list operations.
Why do we need lists?
In the real world, you often need to do the same thing with many objects. For example, you would like to have a list of people in the class. You could use one variable per person, but then you have no way to do something with each person. For this, we use a list.
A list can store multiple items. Each item is called an element.
a = [10, 20, 30]This list has 3 elements.
a = ['Bob', 'Jane', 'John', 'Pete']Lists elements can be any type of variable.
a = [15, 'Pete', 3.14]You can even store different types of elements in the same list.
a = [10]This list has only one element.
a = [['Bob', 'Smith'], ['John', 'Ellison']]A list can even contain other lists.
a = []A list can be empty.
We can see how many elements are in a list by using the len function:
>>>the_class = ['John', 'Jane', 'Pete']
>>>len(the_class)
3The len function gives you the length of the list.
The elements in a list stay in the order they were added. Each element has an index number associated with it. The numbers start at 0.
>>> team = {'Alice', 'Bob', 'Charlie', 'Daniel']
>>> team[0]
'Alice'The first element in the list has index 0.
>>> team[1]
'Bob'
>>> team[2]
'Charlie'
>>> team[3]
'Daniel'Each item can be accessed by using its index.
>>> team[2] = 'Cecil'
>>> team
['Alice', 'Bob', 'Cecil', 'Daniel']
We can change any of the elements in a list, similar to the way we change variables.
>>> team.append('Elaine')
>>> team
['Alice', 'Bob', 'Cecil', 'Daniel', 'Elaine']
We can append elements to the end of the list.
To get only some of the elements of a list, we can slice the list. To do this, we have to specify where in the list we want to start and end. The start index is the first element in the list. The end index is the first element that will NOT be included in the slice.
>>> team[0:1]
['Alice']
>>> team[0:2]
['Alice', 'Bob']
Slicing returns the elements from the index of the beginning of the slice to the element just before the end index.