listA built-in data type in Python is the list. A list is an ordered collection of elements, and you can add or remove elements from it at any time.
For example, to list the names of all classmates in a class, you can use a list:
>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']
The variable classmates is a list. You can use the len() function to get the number of elements in the list:
>>> len(classmates)
3
Access elements at specific positions in the list using an index. Remember that indexing starts at 0:
>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'
>>> classmates[2]
'Tracy'
>>> classmates[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
If the index is out of bounds, Python will raise an IndexError. Therefore, always ensure your index does not exceed the list length. Remember, the index of the last element is len(classmates) - 1.
To get the last element without calculating its index, you can use -1 as the index:
>>> classmates[-1]
'Tracy'
Similarly, you can access the second-to-last, third-to-last, and so on:
>>> classmates[-2]
'Bob'
>>> classmates[-3]
'Michael'
>>> classmates[-4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Of course, trying to access the fourth-to-last element would be out of range.
A list is a mutable ordered sequence. You can append an element to the end of the list:
>>> classmates.append('Adam')
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']
You can also insert an element at a specific position, for example, at index 1:
>>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
To remove the last element from the list, use the pop() method:
>>> classmates.pop()
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']
To remove an element at a specific index i, use pop(i):
>>> classmates.pop(1)
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']
To replace an element with another, simply assign a new value to the corresponding index:
>>> classmates[1] = 'Sarah'
>>> classmates
['Michael', 'Sarah', 'Tracy']
The elements in a list can be of different data types, for example:
>>> L = ['Apple', 123, True]
List elements can also be another list, for example:
>>> s = ['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s)
4
Note that s has only 4 elements, where s[2] is itself a list. This is easier to understand if written separately:
>>> p = ['asp', 'php']
>>> s = ['python', 'java', p, 'scheme']
To access 'php', you can write p[1] or s[2][1]. Therefore, s can be thought of as a two-dimensional array. Similarly, there can be three-dimensional, four-dimensional arrays, and so on, though they are rarely used.
A list with no elements is called an empty list, and its length is 0:
>>> L = []
>>> len(L)
0
tupleAnother type of ordered list is called a tuple. A tuple is very similar to a list, but once initialized, its elements cannot be modified. For example, to list classmates’ names using a tuple:
>>> classmates = ('Michael', 'Bob', 'Tracy')
Now, the tuple classmates cannot be changed. It does not have methods like append() or insert(). However, other methods for accessing elements are the same as for lists. You can normally use classmates[0] or classmates[-1], but you cannot assign a new value to an element.
What is the significance of an immutable tuple? Because a tuple is immutable, it makes the code safer. Whenever possible, use a tuple instead of a list for added safety.
A Tuple Pitfall: When defining a tuple, its elements must be determined at the time of definition. For example:
>>> t = (1, 2)
>>> t
(1, 2)
To define an empty tuple, you can write ():
>>> t = ()
>>> t
()
However, to define a tuple with only one element, if you write:
>>> t = (1)
>>> t
1
You have not defined a tuple; you have defined the number 1! This is because parentheses () can represent both a tuple and parentheses in a mathematical formula, leading to ambiguity. Therefore, Python stipulates that in such cases, the parentheses are treated as mathematical parentheses, resulting in the value 1.
To correctly define a tuple with only one element, you must add a trailing comma , to remove the ambiguity:
>>> t = (1,)
>>> t
(1,)
When displaying a tuple with only one element, Python will also add a trailing comma , to prevent you from mistaking it for a mathematical parenthetical expression.
Finally, let’s look at a “mutable” tuple:
>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])
This tuple was defined with three elements: 'a', 'b', and a list. Wasn’t it stated that a tuple becomes immutable once defined? Why did it change?
Don’t worry. Let’s first look at the three elements the tuple contained when it was defined:
tuple-1 (Conceptual representation: ('a', 'b', [reference_to_list]))
When we modified the list’s elements 'A' and 'B' to 'X' and 'Y', the tuple became:
tuple-2 (Conceptual representation: ('a', 'b', [reference_to_modified_list]))
Superficially, it seems the tuple’s elements have changed. But in reality, it is not the tuple’s elements that changed, but the elements within the list that the tuple points to. The tuple initially pointed to a specific list, and it still points to that same list object; it was never changed to point to a different list. Therefore, the so-called “immutability” of a tuple means that each element of the tuple always points to the same object. That is, if it points to 'a', it cannot be changed to point to 'b'; if it points to a list, it cannot be changed to point to another object. However, the list object itself that it points to can be mutable!
Once you understand this concept of “reference immutability“, how do you create a tuple whose content is also truly immutable? You must ensure that every element of the tuple itself is immutable.
list and tuple are built-in ordered collections in Python, one mutable and the other immutable. Choose them based on your needs.