Lists and Tuples in Python
Lists and Tuples in Python
Tuples” quiz. Upon completion you will receive a score so you can track your
learning progress over time:
— FREE Email Series —
Take the Quiz »
🐍 Python Tricks 💌
Python Lists
In short, a list is a collection of arbitrary objects, somewhat akin to an array in many
other programming languages but more flexible. Lists are defined in Python by
enclosing a comma-separated sequence of objects in square brackets ([]), as shown
below:
Email…
Python >>>
Mark as Completed Tweet Share Email Browse Topics The important characteristics of Python lists are as follows:
Guided Learning Paths
Basics Intermediate Lists are ordered.
Table of Contents Advanced Lists can contain any arbitrary objects.
When you’re finished, you should have a good feel for when and how to use these
>>> [1, 2, 3, 4] == [4, 1, 3, 2]
object types in a Python program. False
Help
Lists Can Contain Arbitrary Objects (A list with a single object is sometimes referred to as a singleton list.)
A list can contain any assortment of objects. The elements of a list can all be the List objects needn’t be unique. A given object can appear in a list multiple times:
same type:
Python >>>
Python >>>
>>> a = ['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
>>> a = [2, 4, 6, 8] >>> a
>>> a ['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
[2, 4, 6, 8]
>>> int The indices for the elements in a are shown below:
<class 'int'>
>>> len
<built-in function len>
>>> def foo():
... pass
...
>>> foo
List Indices
<function foo at 0x035B9030>
>>> import math Here is Python code to access some elements of a:
>>> math
<module 'math' (built-in)> Python >>>
>>> a[0]
>>> a = [int, len, foo, math]
'foo'
>>> a
>>> a[2]
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,
'baz'
<module 'math' (built-in)>]
>>> a[5]
'corge'
A list can contain any number of objects, from zero to as many as your computer’s
memory will allow: Virtually everything about string indexing works similarly for lists. For example, a
negative list index counts from the end of the list:
Python >>>
>>> a = []
>>> a
[]
>>> a = [ 'foo' ]
>>> a
Negative List Indexing
['foo']
Python >>>
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
... 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 >>> a[-1]
... 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 'corge'
... 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 >>> a[-2]
... 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 'quux'
>>> a >>> a[-5]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 'bar'
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, Slicing also works. If a is a list, the expression a[m:n] returns the portion of a from
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, index m to, but not including, index n:
97, 98, 99, 100]
Python >>> Python >>>
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[:]
>>> a[2:5] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
['baz', 'qux', 'quux'] >>> a[:] is a
False
Other features of string slicing work analogously for list slicing as well:
Both positive and negative indices can be specified: Several Python operators and built-in functions can also be used with lists in ways
that are analogous to strings:
Python >>>
The in and not in operators:
>>> a[-5:-2]
['bar', 'baz', 'qux'] >>>
Python
>>> a[1:4]
['bar', 'baz', 'qux'] >>> a
>>> a[-5:-2] == a[1:4] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
True
>>> 'qux' in a
True
Omitting the first index starts the slice at the beginning of the list, and omitting >>> 'thud' not in a
the second index extends the slice to the end of the list: True
Python >>>
The concatenation (+) and replication (*) operators:
>>> print(a[:4], a[0:4])
['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux'] Python >>>
>>> print(a[2:], a[2:len(a)])
['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge'] >>> a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[:4] + a[4:]
['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a + ['grault', 'garply']
>>> a[:4] + a[4:] == a ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
True >>> a * 2
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'foo', 'bar', 'baz',
'qux', 'quux', 'corge']
You can specify a stride—either positive or negative:
>>> a[::-1]
['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
It’s not an accident that strings and lists behave so similarly. They are both special
cases of a more general object type called an iterable, which you will encounter in
The [:] syntax works for lists. However, there is an important difference more detail in the upcoming tutorial on definite iteration.
between how this operation works with a list and how it works with a string.
By the way, in each example above, the list is always assigned to a variable before an
If s is a string, s[:] returns a reference to the same object: operation is performed on it. But you can operate on a list literal as well:
Python >>>
>>> s = 'foobar'
>>> s[:]
'foobar'
>>> s[:] is s
True
>>> ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'][2] >>> print(x[0], x[2], x[4])
'baz' a g j
>>> 'quux' in ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] Python >>>
True
>>> x[1]
['bb', ['ccc', 'ddd'], 'ee', 'ff']
>>> ['foo', 'bar', 'baz'] + ['qux', 'quux', 'corge']
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> x[3]
['hh', 'ii']
>>> len(['foo', 'bar', 'baz', 'qux', 'quux', 'corge'][::-1])
6
To access the items in a sublist, simply append an additional index:
For that matter, you can do likewise with a string literal: >>>
Python
The object structure that x references is diagrammed below: There is no limit, short of the extent of your computer’s memory, to the depth or
complexity with which lists can be nested in this way.
All the usual syntax regarding indices and slicing applies to sublists as well:
Python >>>
>>> x[1][1][-1]
'ddd'
>>> x[1][1:3]
[['ccc', 'ddd'], 'ee']
>>> x[3][::-1]
['ii', 'hh']
However, be aware that operators and functions apply to only the list at the level
you specify and are not recursive. Consider what happens when you query the
A Nested List
length of x using len():
x[0], x[2], and x[4] are strings, each one character long:
Python >>> Python >>>
the sublists don’t count toward x’s length. File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
False
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> 'ddd' in x[1]
False
>>> del a[3]
>>> 'ddd' in x[1][1]
>>> a
True
['foo', 'bar', 'baz', 'quux', 'corge']
'ddd' is not one of the elements in x or x[1]. It is only directly an element in the
sublist x[1][1]. An individual element in a sublist does not count as an element of
the parent list(s). Modifying Multiple List Values
What if you want to change several contiguous elements in a list at one time? Python
allows this with slice assignment, which has the following syntax:
Python
Remove ads
a[m:n] = <iterable>
Lists Are Mutable Again, for the moment, think of an iterable as a list. This assignment replaces the
specified slice of a with <iterable>:
Most of the data types you have encountered so far have been atomic types. Integer
or float objects, for example, are primitive units that can’t be further broken down. Python >>>
These types are immutable, meaning that they can’t be changed once they have
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
been assigned. It doesn’t make much sense to think of changing the value of an
integer. If you want a different integer, you just assign a different one. >>> a[1:4]
['bar', 'baz', 'qux']
By contrast, the string type is a composite type. Strings are reducible to smaller >>> a[1:4] = [1.1, 2.2, 3.3, 4.4, 5.5]
parts—the component characters. It might make sense to think of changing the >>> a
['foo', 1.1, 2.2, 3.3, 4.4, 5.5, 'quux', 'corge']
characters in a string. But you can’t. In Python, strings are also immutable.
>>> a[1:6]
[1.1, 2.2, 3.3, 4.4, 5.5]
The list is the first mutable data type you have encountered. Once a list has been
>>> a[1:6] = ['Bark!']
created, elements can be added, deleted, shifted, and moved around at will. Python >>> a
provides a wide range of ways to modify lists. ['foo', 'Bark!', 'quux', 'corge']
Modifying a Single List Value The number of elements inserted need not be equal to the number replaced. Python
just grows or shrinks the list as needed.
A single value in a list can be replaced by indexing and simple assignment:
You can insert multiple elements in place of a single element—just use a slice that
denotes only one element:
Python >>> Python >>>
Python >>> Strings are iterable also. But watch what happens when you concatenate a
string onto a list:
>>> a = [1, 2, 7, 8]
>>> a[2:2] = [3, 4, 5, 6] Python >>>
>>> a
[1, 2, 3, 4, 5, 6, 7, 8] >>> a = ['foo', 'bar', 'baz', 'qux', 'quux']
>>> a += 'corge'
>>> a
You can delete multiple elements out of the middle of a list by assigning the ['foo', 'bar', 'baz', 'qux', 'quux', 'c', 'o', 'r', 'g', 'e']
appropriate slice to an empty list. You can also use the del statement with the same
slice:
This result is perhaps not quite what you expected. When a string is iterated
Python >>> through, the result is a list of its component characters. In the above example,
what gets concatenated onto list a is a list of the characters in the string
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
'corge'.
>>> a[1:5] = []
>>> a
['foo', 'corge']
If you really want to add just the single string 'corge' to the end of the list, you
need to specify it as a singleton list:
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> del a[1:5] Python >>>
>>> a
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux']
['foo', 'corge']
>>> a += ['corge']
>>> a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
Python >>>
Methods That Modify a List
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
Finally, Python supplies several built-in methods that can be used to modify lists.
>>> a += ['grault', 'garply'] Information on these methods is detailed below.
>>> a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
Note: The string methods you saw in the previous tutorial did not modify the
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] target string directly. That is because strings are immutable. Instead, string
methods return a new string object that is modified as directed by the method.
>>> a = [10, 20] + a
They leave the original target string unchanged:
>>> a
[10, 20, 'foo', 'bar', 'baz', 'qux', 'quux', 'corge']
Python >>>
>>> s = 'foobar'
Note that a list must be concatenated with another list, so if you want to add only >>> t = s.upper()
one element, you need to specify it as a singleton list: >>> print(s, t)
foobar FOOBAR
List methods are different. Because lists are mutable, the list methods shown Yes, this is probably what you think it is. .extend() also adds to the end of a list, but
here modify the target list in place. the argument is expected to be an iterable. The items in <iterable> are added
individually:
Python >>>
a.append(<obj>)
>>> a = ['a', 'b']
>>> a.extend([1, 2, 3])
Appends an object to a list. >>> a
['a', 'b', 1, 2, 3]
a.append(<obj>) appends object <obj> to the end of list a:
In other words, .extend() behaves like the + operator. More precisely, since it
Python >>>
modifies the list in place, it behaves like the += operator:
>>> a = ['a', 'b']
>>> a.append(123) Python >>>
>>> a
['a', 'b', 123] >>> a = ['a', 'b']
>>> a += [1, 2, 3]
>>> a
Remember, list methods modify the target list in place. They do not return a new list: ['a', 'b', 1, 2, 3]
Python >>>
a.insert(<index>, <obj>) inserts object <obj> into list a at the specified <index>.
Remember that when the + operator is used to concatenate to a list, if the target Following the method call, a[<index>] is <obj>, and the remaining list elements are
operand is an iterable, then its elements are broken out and appended to the list pushed to the right:
individually:
Python >>>
Python >>>
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
Python >>>
a.remove(<obj>)
>>> a = ['a', 'b']
>>> a.append([1, 2, 3])
Removes an object from a list.
>>> a
['a', 'b', [1, 2, 3]]
a.remove(<obj>) removes object <obj> from list a. If <obj> isn’t in a, an exception is
raised:
Thus, with .append(), you can append a string as a single entity:
Python >>>
Python >>>
>>> a.remove('Bark!')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a.remove('Bark!')
a.extend(<iterable>) ValueError: list.remove(x): x not in list
1. You specify the index of the item to remove, rather than the object itself.
2. The method returns a value: the item that was removed.
a.pop() simply removes the last item in the list: Python Tuples
Python >>> Python provides another type that is an ordered collection of objects, called a tuple.
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] Pronunciation varies depending on whom you ask. Some pronounce it as though it
were spelled “too-ple” (rhyming with “Mott the Hoople”), and others as though it
>>> a.pop()
'corge'
were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter, since it
>>> a presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and
['foo', 'bar', 'baz', 'qux', 'quux'] so on, and everyone I know pronounces these latter as though they rhymed with
“supple.”
>>> a.pop()
'quux'
>>> a
['foo', 'bar', 'baz', 'qux']
Defining and Using Tuples
Tuples are identical to lists in all respects, except for the following properties:
If the optional <index> parameter is specified, the item at that index is removed and
Tuples are defined by enclosing the elements in parentheses (()) instead of
returned. <index> may be negative, as with string and list indexing:
square brackets ([]).
Python >>> Tuples are immutable.
Never fear! Our favorite string and list reversal mechanism works for tuples as well:
Python >>>
Remove ads
>>> t[::-1]
('corge', 'quux', 'qux', 'baz', 'bar', 'foo')
Lists Are Dynamic
This tutorial began with a list of six defining characteristics of Python lists. The last
Note: Even though tuples are defined using parentheses, you still index and
one is that lists are dynamic. You have seen many examples of this in the sections
slice tuples using square brackets, just as for strings and lists.
above. When items are added to a list, it grows as needed:
Python >>> Everything you’ve learned about lists—they are ordered, they can contain arbitrary
objects, they can be indexed and sliced, they can be nested—is true of tuples as well.
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
But they can’t be modified:
>>> a[2:2] = [1, 2, 3]
>>> a += [3.14159]
>>> a
['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159]
Sometimes you don’t want data to be modified. If the values in the collection You probably won’t need to define a singleton tuple often, but there has to be a way.
are meant to remain constant for the life of the program, using a tuple instead
of a list guards against accidental modification. When you display a singleton tuple, Python includes the comma, to remind you that
it’s a tuple:
There is another Python data type that you will encounter shortly called a
dictionary, which requires as one of its components a value that is of an Python >>>
immutable type. A tuple can be used for this purpose, whereas a list can’t be. >>> print(t)
(2,)
In a Python REPL session, you can display the values of several objects
simultaneously by entering them directly at the >>> prompt, separated by commas:
Python >>>
>>> a = 'foo'
Remove ads
>>> b = 42
>>> a, 3.14159, b
('foo', 3.14159, 42)
Tuple Assignment, Packing, and Unpacking
Python displays the response in parentheses because it is implicitly interpreting the As you have already seen above, a literal tuple containing several items can be
input as a tuple. assigned to a single object:
Python >>>
There is one peculiarity regarding tuple definition that you should be aware of.
There is no ambiguity when defining an empty tuple, nor one with two or more >>> t = ('foo', 'bar', 'baz', 'qux')
elements. Python knows you are defining a tuple:
>>>
When this occurs, it is as though the items in the tuple have been “packed” into the
Python
object:
>>> t = ()
>>> type(t)
<class 'tuple'>
Python >>>
>>> t = (1, 2)
>>> type(t)
<class 'tuple'>
>>> t = (1, 2, 3, 4, 5)
>>> type(t)
<class 'tuple'>
Tuple Packing
But what happens when you try to define a tuple with one item: Python >>>
are “unpacked” into the objects in the tuple: >>> (s1, s2, s3, s4, s5) = ('foo', 'bar', 'baz', 'qux')
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
(s1, s2, s3, s4, s5) = ('foo', 'bar', 'baz', 'qux')
ValueError: not enough values to unpack (expected 5, got 4)
In assignments like this and a small handful of other situations, Python allows the
parentheses that are usually used for denoting a tuple to be left out:
Python >>>
>>> t = 1, 2, 3
>>> t
(1, 2, 3)
Tuple Unpacking
>>> x1, x2, x3 = t
>>> x1, x2, x3
Python >>>
(1, 2, 3)
>>> (s1, s2, s3, s4) = t
>>> s1 >>> x1, x2, x3 = 4, 5, 6
'foo' >>> x1, x2, x3
>>> s2 (4, 5, 6)
'bar'
>>> s3 >>> t = 2,
'baz' >>> t
>>> s4 (2,) Table of Contents
'qux' Python Lists
It works the same whether the parentheses are included or not, so if you have any Python Tuples
When unpacking, the number of variables on the left must match the number of doubt as to whether they’re needed, go ahead and include them. → Conclusion
assignment:
>>> a, b
>>>
('bar', 'foo')
Python
'bar'
>>> a = 'foo'
>>> s3
>>> b = 'bar'
'baz'
>>> a, b
>>> s4
('foo', 'bar')
'qux'
John is an avid Pythonista and a member of the Real Python tutorial team.
Remove ads
Conclusion
This tutorial covered the basic properties of Python lists and tuples, and how to
manipulate them. You will use these extensively in your Python programming.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who
One of the chief characteristics of a list is that it is ordered. The order of the
worked on this tutorial are:
elements in a list is an intrinsic property of that list and does not change, unless the
list itself is modified. (The same is true of tuples, except of course they can’t be
modified.)
Aldren Dan Joanna
The next tutorial will introduce you to the Python dictionary: a composite data type
that is unordered. Read on!
Take the Quiz: Test your knowledge with our interactive “Python Lists and
Tuples” quiz. Upon completion you will receive a score so you can track your
learning progress over time: Master Real-World Python Skills
Take the Quiz »
With Unlimited Access to Real Python
Mark as Completed
Watch Now This tutorial has a related video course created by the Real
Python team. Watch it together with the written tutorial to deepen your
understanding: Lists and Tuples in Python
Join us and get access to thousands of
tutorials, hands-on video courses, and
a community of expert Pythonistas:
🐍 Python Tricks 💌
Level Up Your Python Skills »
Get a short & sweet Python Trick delivered to your inbox every couple of
days. No spam ever. Unsubscribe any time. Curated by the Real Python
team.
What’s your #1 takeaway or favorite thing you learned? How are you going to
Email Address put your newfound skills to use? Leave a comment below and let us know.
Send Me Python Tricks » Commenting Tips: The most useful comments are those written with the
goal of learning from or helping out other students. Get tips for asking
good questions and get answers to common questions in our support
portal.
Keep Learning
Remove ads