Python Lists and Tuples
Learn how to create lists in Python and recall their items.
Lists
In programming, sometimes we need to deal with a list of values that are related. In Python, a list is a single value which contains many other values deeper within. A Python list expression looks like this:
>>> ['English', 'Spanish', 'Russian']
['English', 'Spanish', 'Russian']
>>> some_list = ['abcd', 1234, 'another list item']
Each item in a list is automatically given an index, which is a number (starting from zero) that can be used to recall that item later. This index is put in square brackets after an expression which yields the list, such as a variable that holds it or a list expression, and the combined expression evaluates to the value at that index.
>>> some_list[0]
'abcd'
>>> ['a', 'b', 'c', 'd', 'e'][3]
'd'
Tuples
When we don't need to be able to modify the list's items later on in the Python code, we use parenthesis instead of square brackets in the expression to create the list. When we use parenthesis, the list is called a tuple. Parenthesis make the list immutable, meaning that in order to modify it, the system needs to erase the whole list and build it again in the memory. Immutable values yield better system performance, so we use parenthesis whenever the list doesn't need to change while Python is running.
>>> list1 = ('a', 'b', 'c')
>>> list2 = ('a',)
>>> list1[2]
'c'When there is only one value in the tuple, we put a comma after it anyway so that Python knows the parenthesis denote a tuple as opposed to instructions for order of operation (as for arithmetic). When recalling a value from a tuple, we still use square brackets.
Modifying List Variable Items
A single item in a list variable can be set just like a regular variable.
>>> list3 = ['a', 'b', 'c']
>>> list3
['a', 'b', 'c']
>>> list3[1] = 'no longer "b"'
>>> list3
['a', 'no longer "b"', 'c']