[go: up one dir, main page]

0% found this document useful (0 votes)
16 views12 pages

Lists and Tuples in Python

Uploaded by

dhanunjayav2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

Lists and Tuples in Python

Uploaded by

dhanunjayav2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

 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:
— 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 >>>

>>> a = ['foo', 'bar', 'baz', 'qux']


Get Python Tricks »

Lists and Tuples in Python 🔒 No spam. Unsubscribe any >>> print(a)


['foo', 'bar', 'baz', 'qux']
by John Sturtz  Jul 18, 2018  27 Comments time. >>> a
 basics python ['foo', 'bar', 'baz', 'qux']

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.

Python Lists List elements can be accessed by index.


api best-practices career
Lists Are Ordered Lists can be nested to arbitrary depth.
community databases data-science
Lists Can Contain Arbitrary Objects data-structures data-viz devops Lists are mutable.
List Elements Can Be Accessed by Index django docker editors flask Lists are dynamic.
Lists Can Be Nested front-end gamedev gui
Lists Are Mutable Each of these features is examined in more detail below.
machine-learning numpy projects
Lists Are Dynamic python testing tools web-dev
Python Tuples web-scraping
Defining and Using Tuples
Tuple Assignment, Packing, and Unpacking
 Remove ads
Conclusion

Lists Are Ordered


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
 Remove ads 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.)
 Watch Now This tutorial has a related video course created by the Real
Lists that have the same elements in a different order are not the same:
Python team. Watch it together with the written tutorial to deepen your
understanding: Lists and Tuples in Python Python >>>

>>> a = ['foo', 'bar', 'baz', 'qux']


Lists and tuples are arguably Python’s most versatile, useful data types. You will >>> b = ['baz', 'qux', 'bar', 'foo']
find them in virtually every nontrivial Python program. >>> a == b
False
Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics >>> a is b
of lists and tuples. You’ll learn how to define them and how to manipulate them. False

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]

Or the elements can be of varying types:


List Elements Can Be Accessed by Index
Python >>>
Individual elements in a list can be accessed using an index in square brackets. This
>>> a = [21.42, 'foobar', 3, 4, 'bark', False, 3.14159] is exactly analogous to accessing individual characters in a string. List indexing is
>>> a zero-based as it is with strings.
[21.42, 'foobar', 3, 4, 'bark', False, 3.14159]

Consider the following list:


Lists can even contain complex objects, like functions, classes, and modules, which
Python >>>
you will learn about in upcoming tutorials:
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
Python >>>

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

Python >>> The len(), min(), and max() functions:

>>> a[0:6:2] Python >>>


['foo', 'baz', 'quux']
>>> a[1:6:2] >>> a
['bar', 'qux', 'corge'] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[6:0:-2]
['corge', 'qux', 'bar'] >>> len(a)
6
>>> min(a)
The syntax for reversing a list works the same way it does for strings: 'bar'
>>> max(a)
Python >>> 'qux'

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

Conversely, if a is a list, a[:] returns a new object that is a copy of a:


Python >>> Python >>>

>>> ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'][2] >>> print(x[0], x[2], x[4])
'baz' a g j

>>> ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'][::-1]


['corge', 'quux', 'qux', 'baz', 'bar', 'foo'] But x[1] and x[3] are sublists:

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

Python >>> >>> x[1]


['bb', ['ccc', 'ddd'], 'ee', 'ff']
>>> 'If Comrade Napoleon says it, it must be right.'[::-1]
'.thgir eb tsum ti ,ti syas noelopaN edarmoC fI'
>>> x[1][0]
'bb'
>>> x[1][1]
['ccc', 'ddd']
>>> x[1][2]
'ee'
 Remove ads >>> x[1][3]
'ff'

Lists Can Be Nested >>> x[3]


['hh', 'ii']
You have seen that an element in a list can be any sort of object. That includes >>> print(x[3][0], x[3][1])
another list. A list can contain sublists, which in turn can contain sublists hh ii

themselves, and so on to arbitrary depth.


x[1][1] is yet another sublist, so adding one more index accesses its elements:
Consider this (admittedly contrived) example:
Python >>>
Python >>>
>>> x[1][1]
>>> x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] ['ccc', 'ddd']
>>> x >>> print(x[1][1][0], x[1][1][1])
['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] ccc ddd

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

>>> x >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']


['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] >>> a
>>> len(x) ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
5
>>> a[2] = 10
>>> x[0] >>> a[-1] = 20
'a' >>> a
>>> x[1] ['foo', 'bar', 10, 'qux', 'quux', 20]
['bb', ['ccc', 'ddd'], 'ee', 'ff']
>>> x[2]
'g' You may recall from the tutorial Strings and Character Data in Python that you can’t
>>> x[3] do this with a string:
['hh', 'ii']
>>> x[4] Python >>>
'j'
>>> s = 'foobarbaz'
>>> s[2] = 'x'
x has only five elements—three strings and two sublists. The individual elements in Traceback (most recent call last):

the sublists don’t count toward x’s length. File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

You’d encounter a similar situation when using the in operator:


A list item can be deleted with the del command:
Python >>>

>>> 'ddd' in x Python >>>

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

>>> a = [1, 2, 3] >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']


>>> a[1:2] = [2.1, 2.2, 2.3] >>> a += 20
>>> a Traceback (most recent call last):
[1, 2.1, 2.2, 2.3, 3] File "<pyshell#58>", line 1, in <module>
a += 20
TypeError: 'int' object is not iterable
Note that this is not the same as replacing the single element with a list:
>>> a += [20]
Python >>> >>> a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 20]
>>> a = [1, 2, 3]
>>> a[1] = [2.1, 2.2, 2.3]
>>> a
[1, [2.1, 2.2, 2.3], 3] Note: Technically, it isn’t quite correct to say a list must be concatenated with
another list. More precisely, a list must be concatenated with an object that is
You can also insert elements into a list without removing anything. Simply specify a iterable. Of course, lists are iterable, so it works to concatenate a list with
slice of the form [n:n] (a zero-length slice) at the desired index: another list.

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']

Prepending or Appending Items to a List


If this seems mysterious, don’t fret too much. You’ll learn about the ins and
Additional items can be added to the start or end of a list using the + concatenation
outs of iterables in the tutorial on definite iteration.
operator or the += augmented assignment operator:

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 = ['a', 'b']


>>> x = a.append(123)
>>> print(x)
a.insert(<index>, <obj>)
None
>>> a Inserts an object into a list.
['a', 'b', 123]

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']

>>> a = ['a', 'b'] >>> a.insert(3, 3.14159)


>>> a[3]
>>> a + [1, 2, 3]
['a', 'b', 1, 2, 3] 3.14159
>>> a
['foo', 'bar', 'baz', 3.14159, 'qux', 'quux', 'corge']
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 >>>
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 = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']


>>> a = ['a', 'b']
>>> a.remove('baz')
>>> a.append('foo')
>>> a
>>> a
['foo', 'bar', 'qux', 'quux', 'corge']
['a', 'b', 'foo']

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

Extends a list with the objects from an iterable.


a.pop(index=-1) Python >>>

>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']


Removes an element from a list. >>> a[2:3] = []
>>> del a[0]
This method differs from .remove() in two ways: >>> a
['bar', 'qux', 'quux', 'corge']

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.

>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']


Here is a short example showing a tuple definition, indexing, and slicing:
>>> a.pop(1)
Python >>>
'bar'
>>> a >>> t = ('foo', 'bar', 'baz', 'qux', 'quux', 'corge')
['foo', 'baz', 'qux', 'quux', 'corge'] >>> t
('foo', 'bar', 'baz', 'qux', 'quux', 'corge')
>>> a.pop(-3)
'qux' >>> t[0]
>>> a 'foo'
['foo', 'baz', 'quux', 'corge'] >>> t[-1]
'corge'
>>> t[1::2]
<index> defaults to -1, so a.pop(-1) is equivalent to a.pop(). ('bar', 'qux', 'corge')

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]

Similarly, a list shrinks to accommodate the removal of items:


Python >>> Doh! Since parentheses are also used to define operator precedence in expressions,
>>> t = ('foo', 'bar', 'baz', 'qux', 'quux', 'corge') Python evaluates the expression (2) as simply the integer 2 and creates an int
>>> t[2] = 'Bark!' object. To tell Python that you really want to define a singleton tuple, include a
Traceback (most recent call last): trailing comma (,) just before the closing parenthesis:
File "<pyshell#65>", line 1, in <module>
t[2] = 'Bark!' Python >>>
TypeError: 'tuple' object does not support item assignment
>>> t = (2,)
>>> type(t)
Why use a tuple instead of a list? <class 'tuple'>
>>> t[0]
Program execution is faster when manipulating a tuple than it is for the 2
equivalent list. (This is probably not going to be noticeable when the list or >>> t[-1]
2
tuple is small.)

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

Python >>> >>> t


('foo', 'bar', 'baz', 'qux')
>>> t = (2) >>> t[0]
>>> type(t)
'foo'
<class 'int'> >>> t[-1]
'qux'
If that “packed” object is subsequently assigned to a new tuple, the individual items 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

values in the tuple:


Tuple assignment allows for a curious bit of idiomatic Python. Frequently when
Mark as Completed 
Python >>> programming, you have two variables whose values you need to swap. In most
>>> (s1, s2, s3) = t programming languages, it is necessary to store one of the values in a temporary
Traceback (most recent call last): variable while the swap occurs like this:
File "<pyshell#16>", line 1, in <module>
 Tweet  Share  Email
(s1, s2, s3) = t Python >>>
ValueError: too many values to unpack (expected 3)
>>> a = 'foo'
>>> b = 'bar'  Recommended Video Course
>>> (s1, s2, s3, s4, s5) = t
Traceback (most recent call last):
>>> a, b Lists and Tuples in Python
File "<pyshell#17>", line 1, in <module> ('foo', 'bar')

(s1, s2, s3, s4, s5) = t


>>># We need to define a temp variable to accomplish the swap.
ValueError: not enough values to unpack (expected 5, got 4)
>>> temp = a
>>> a = b
Packing and unpacking can be combined into one statement to make a compound >>> b = temp

assignment:
>>> a, b
>>>
('bar', 'foo')
Python

>>> (s1, s2, s3, s4) = ('foo', 'bar', 'baz', 'qux')


>>> s1 In Python, the swap can be done with a single tuple assignment:
'foo'
>>> s2 Python >>>

'bar'
>>> a = 'foo'
>>> s3
>>> b = 'bar'
'baz'
>>> a, b
>>> s4
('foo', 'bar')
'qux'

>>># Magic time!


>>> a, b = b, a
Again, the number of elements in the tuple on the left of the assignment must equal
the number on the right: >>> a, b
('bar', 'foo')
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 About John Sturtz
achievement. It will never get better than this.

John is an avid Pythonista and a member of the Real Python tutorial team.

» More about John

 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

« Strings in Python Lists and Tuples in Python Dictionaries in 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 Do You Think?

Rate this article:

 Tweet  Share  Share  Email

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.

Looking for a real-time conversation? Visit the Real Python Community


Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Tutorial Categories: basics python

Recommended Video Course: Lists and Tuples in Python

 Remove ads

© 2012–2023 Real Python ⋅ Newsletter ⋅ Podcast ⋅ YouTube ⋅ Twitter ⋅ Facebook ⋅ Instagram ⋅


Python Tutorials ⋅ Search ⋅ Privacy Policy ⋅ Energy Policy ⋅ Advertise ⋅ Contact
❤️ Happy Pythoning!

You might also like