Skip to content
On this page

Using list and tuple

list

One of Python's built-in data types is the list. A list is an ordered collection that allows you to add and remove elements at any time.

For example, to list all the names of students in a class, you can use a list:

python
>>> 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:

python
>>> len(classmates)
3

Use indexing to access each element in the list. Remember that indexing starts at 0:

python
>>> 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

When the index is out of range, Python raises an IndexError. Therefore, ensure that the index does not exceed the range. Remember that the index of the last element is len(classmates) - 1.

If you want to retrieve the last element, besides calculating the index position, you can also use -1 as the index to directly get the last element:

python
>>> classmates[-1]
'Tracy'

Similarly, you can get the second-to-last and third-to-last elements:

python
>>> 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, the fourth-to-last element is out of range.

A list is a mutable ordered table, so you can append elements to the end of the list:

python
>>> classmates.append('Adam')
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']

You can also insert elements at a specific position, such as index 1:

python
>>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

To remove the last element from the list, use the pop() method:

python
>>> classmates.pop()
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']

To remove an element at a specific position, use pop(i), where i is the index:

python
>>> classmates.pop(1)
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']

To replace an element with another, you can directly assign a new value to the corresponding index:

python
>>> classmates[1] = 'Sarah'
>>> classmates
['Michael', 'Sarah', 'Tracy']

Elements within a list can be of different data types. For example:

python
>>> L = ['Apple', 123, True]

Elements in a list can also be another list:

python
>>> s = ['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s)
4

Note that s has only 4 elements, where s[2] is another list. Writing it separately makes it easier to understand:

python
>>> p = ['asp', 'php']
>>> s = ['python', 'java', p, 'scheme']

To access 'php', you can use p[1] or s[2][1]. Therefore, s can be considered a two-dimensional array. Similarly, there are three-dimensional, four-dimensional, etc., arrays, but they are rarely used.

If a list has no elements, it is an empty list with a length of 0:

python
>>> L = []
>>> len(L)
0

tuple

Another ordered list is the tuple. Tuples are very similar to lists, but once a tuple is initialized, it cannot be modified. For example, to list the names of classmates:

python
>>> classmates = ('Michael', 'Bob', 'Tracy')

Now, the classmates tuple cannot be changed. It does not have methods like append() or insert(). Other methods for accessing elements are the same as for lists. You can use classmates[0] and classmates[-1] normally, but you cannot assign new values to elements.

What is the significance of an immutable tuple? Because tuples are immutable, the code is safer. If possible, use tuples instead of lists.

The Trap of Tuples: When you define a tuple, the elements of the tuple must be determined at the time of definition. For example:

python
>>> t = (1, 2)
>>> t
(1, 2)

To define an empty tuple, you can write ():

python
>>> t = ()
>>> t
()

However, to define a tuple with only one element, if you write:

python
>>> t = (1)
>>> t
1

It is not a tuple; it is the number 1. This is because parentheses () can represent both tuples and mathematical expressions, creating ambiguity. Therefore, Python stipulates that in this case, the parentheses are treated as part of a mathematical expression, and the result is naturally 1.

So, to define a tuple with only one element, you must add a comma , to eliminate ambiguity:

python
>>> t = (1,)
>>> t
(1,)

Python also displays a comma , when showing a tuple with only one element to prevent misunderstanding it as a mathematical expression's parentheses.

Finally, let's look at a "mutable" tuple:

python
>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

This tuple is defined with three elements: 'a', 'b', and a list. Isn't the tuple supposed to be immutable once defined? How did it change later?

Don't worry, let's first look at the three elements contained in the tuple when it was defined:

tuple-step-1.png

After modifying the list elements 'A' and 'B' to 'X' and 'Y', the tuple becomes:

tuple-step-2.png

On the surface, it appears that the elements of the tuple have indeed changed. However, what actually changed is not the elements of the tuple but the elements within the list. The tuple initially points to the list, and the list itself was modified, not replaced with another list. Therefore, the "immutability" of a tuple means that each element of the tuple always points to the same object. If an element points to 'a', it cannot be changed to point to 'b'; if it points to a list, it cannot point to another object. However, the list itself that it points to is mutable!

Understanding "Immutable References": After understanding "immutable references," how can you create a tuple with content that also does not change? You must ensure that each element within the tuple itself is also immutable.

Exercise

Use indexing to retrieve the specified elements from the following list:

python
L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Bob']
]

# Print 'Apple':
print(L[0][0])
# Print 'Python':
print(L[1][1])
# Print 'Bob':
print(L[2][2])

Which of the following variables are of tuple type?

python
a = ()
b = (1)
c = [2]
d = (3,)
e = (4, 5, 6)

Summary

list and tuple are Python's built-in ordered collections—one mutable and the other immutable. Choose between them based on your needs.

Using list and tuple has loaded