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
Lists and tuples are arguably Python’s most versatile, useful data types. You will find them in virtually every nontrivial Python program.
Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.
Take the Quiz: Test your knowledge with our interactive “Python Lists and Tuples” quiz. You’ll receive a score upon completion to help you track your learning progress:
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:
Python
The important characteristics of Python lists are as follows:
Each of these features is examined in more detail below.
A list is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime. (You will see a Python data type that is not ordered in the next tutorial on dictionaries.)
Lists that have the same elements in a different order are not the same:
Python
A list can contain any assortment of objects. The elements of a list can all be the same type:
Python
Or the elements can be of varying types:
Python
Lists can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming tutorials:
Python
A list can contain any number of objects, from zero to as many as your computer’s memory will allow:
Python
(A list with a single object is sometimes referred to as a singleton list.)
List objects needn’t be unique. A given object can appear in a list multiple times:
Python
Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings.
Consider the following list:
Python
The indices for the elements in a are shown below:
Here is Python code to access some elements of a:
Python
Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:
Python
Slicing also works. If a is a list, the expression a[m:n] returns the portion of a from index m to, but not including, index n:
Python
Other features of string slicing work analogously for list slicing as well:
Both positive and negative indices can be specified:
Python
Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end of the list:
Python
You can specify a stride—either positive or negative:
Python
The syntax for reversing a list works the same way it does for strings:
Python
The [:] syntax works for lists. However, there is an important difference between how this operation works with a list and how it works with a string.
If s is a string, s[:] returns a reference to the same object:
Python
Conversely, if a is a list, a[:] returns a new object that is a copy of a:
Python
Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:
The in and not in operators:
Python
The concatenation (+) and replication (*) operators:
Python
The len(), min(), and max() functions:
Python
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 more detail in the upcoming tutorial on definite iteration.
By the way, in each example above, the list is always assigned to a variable before an operation is performed on it. But you can operate on a list literal as well:
Python
For that matter, you can do likewise with a string literal:
Python
You have seen that an element in a list can be any sort of object. That includes another list. A list can contain sublists, which in turn can contain sublists themselves, and so on to arbitrary depth.
Consider this (admittedly contrived) example:
Python
The object structure that x references is diagrammed below:
x[0], x[2], and x[4] are strings, each one character long:
Python
But x[1] and x[3] are sublists:
Python
To access the items in a sublist, simply append an additional index:
Python
x[1][1] is yet another sublist, so adding one more index accesses its elements:
Python
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
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 length of x using len():
Python
x has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward x’s length.
You’d encounter a similar situation when using the in operator:
Python
'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).
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. These types are immutable, meaning that they can’t be changed once they have 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.
By contrast, the string type is a composite type. Strings are reducible to smaller parts—the component characters. It might make sense to think of changing the characters in a string. But you can’t. In Python, strings are also immutable.
The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted, shifted, and moved around at will. Python provides a wide range of ways to modify lists.
A single value in a list can be replaced by indexing and simple assignment:
Python
You may recall from the tutorial Strings and Character Data in Python that you can’t do this with a string:
Python
A list item can be deleted with the del command:
Python
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
Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of a with <iterable>:
Python
The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed.
You can insert multiple elements in place of a single element—just use a slice that denotes only one element:
Python
Note that this is not the same as replacing the single element with a list:
Python
You can also insert elements into a list without removing anything. Simply specify a slice of the form [n:n] (a zero-length slice) at the desired index:
Python
You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also use the del statement with the same slice:
Python
Additional items can be added to the start or end of a list using the + concatenation operator or the += augmented assignment operator:
Python
Note that a list must be concatenated with another list, so if you want to add only one element, you need to specify it as a singleton list:
Python
Finally, Python supplies several built-in methods that can be used to modify lists. Information on these methods is detailed below.
a.append(<obj>)
Appends an object to a list.
a.append(<obj>) appends object <obj> to the end of list a:
Python
Remember, list methods modify the target list in place. They do not return a new list:
Python
Remember that when the + operator is used to concatenate to a list, if the target operand is an iterable, then its elements are broken out and appended to the list individually:
Python
The .append() method does not work that way! If an iterable is appended to a list with .append(), it is added as a single object:
Python
Thus, with .append(), you can append a string as a single entity:
Python
a.extend(<iterable>)
Extends a list with the objects from an iterable.
Yes, this is probably what you think it is. .extend() also adds to the end of a list, but the argument is expected to be an iterable. The items in <iterable> are added individually:
Python
In other words, .extend() behaves like the + operator. More precisely, since it modifies the list in place, it behaves like the += operator:
Python
a.insert(<index>, <obj>)
Inserts an object into a list.
a.insert(<index>, <obj>) inserts object <obj> into list a at the specified <index>. Following the method call, a[<index>] is <obj>, and the remaining list elements are pushed to the right:
Python
a.remove(<obj>)
Removes an object from a list.
a.remove(<obj>) removes object <obj> from list a. If <obj> isn’t in a, an exception is raised:
Python
a.pop(index=-1)
Removes an element from a list.
This method differs from .remove() in two ways:
a.pop() simply removes the last item in the list:
Python
If the optional <index> parameter is specified, the item at that index is removed and returned. <index> may be negative, as with string and list indexing:
Python
<index> defaults to -1, so a.pop(-1) is equivalent to a.pop().
This tutorial began with a list of six defining characteristics of Python lists. The last one is that lists are dynamic. You have seen many examples of this in the sections above. When items are added to a list, it grows as needed:
Python
Similarly, a list shrinks to accommodate the removal of items:
Python
Python provides another type that is an ordered collection of objects, called a tuple.
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 were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter, since it presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and so on, and everyone I know pronounces these latter as though they rhymed with “supple.”
Tuples are identical to lists in all respects, except for the following properties:
()) instead of square brackets ([]).Here is a short example showing a tuple definition, indexing, and slicing:
Python
Never fear! Our favorite string and list reversal mechanism works for tuples as well:
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. But they can’t be modified:
Python
Why use a tuple instead of a list?
Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)
Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.
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 immutable type. A tuple can be used for this purpose, whereas a list can’t be.
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
Python displays the response in parentheses because it is implicitly interpreting the input as a tuple.
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 elements. Python knows you are defining a tuple:
Python
Python
But what happens when you try to define a tuple with one item:
Python
Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression (2) as simply the integer 2 and creates an int object. To tell Python that you really want to define a singleton tuple, include a trailing comma (,) just before the closing parenthesis:
Python
You probably won’t need to define a singleton tuple often, but there has to be a way.
When you display a singleton tuple, Python includes the comma, to remind you that it’s a tuple:
Python
As you have already seen above, a literal tuple containing several items can be assigned to a single object:
Python
When this occurs, it is as though the items in the tuple have been “packed” into the object:
Python
If that “packed” object is subsequently assigned to a new tuple, the individual items are “unpacked” into the objects in the tuple:
Python
When unpacking, the number of variables on the left must match the number of values in the tuple:
Python
Packing and unpacking can be combined into one statement to make a compound assignment:
Python
Again, the number of elements in the tuple on the left of the assignment must equal the number on the right:
Python
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
It works the same whether the parentheses are included or not, so if you have any doubt as to whether they’re needed, go ahead and include them.
Tuple assignment allows for a curious bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it is necessary to store one of the values in a temporary variable while the swap occurs like this:
Python
In Python, the swap can be done with a single tuple assignment:
Python
As anyone who has ever had to swap values using a temporary variable knows, being able to do it this way in Python is the pinnacle of modern technological achievement. It will never get better than this.
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.
One of the chief characteristics of a list is that it is ordered. The order of the 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.)
The next tutorial will introduce you to the Python dictionary: a composite data type that is unordered. Read on!
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