Warning: session_start(): open(/tmp/sess_8b0cb0dcb371664d16e323fa91d619ae, O_RDWR) failed: Disk quota exceeded (122) in /home/wvyrfnwn/learnshareit.com/wp-content/plugins/learnpress/inc/class-lp-page-controller.php on line 1007

Warning: session_start(): Failed to read session data: files (path: /tmp) in /home/wvyrfnwn/learnshareit.com/wp-content/plugins/learnpress/inc/class-lp-page-controller.php on line 1007

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 719

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 719

Warning: ftp_mkdir() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 562

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230
Python Tuples: How To Create And Use Them

Python Tuples: How To Create And Use Them

Python Tuples

Many beginners find Python tuples and lists confusing. They look and behave pretty much the same at first glance. However, these powerful data structures co-exist for a reason. You will know about this comparison and how you can make use of tuples after this article.

Python Tuples

What Is A Tuple?

The best way to understand tuples is to think of them as immutable lists. You can store items of any type in these collections in an ordered manner.

However, you can’t change a tuple in any way after creating it. This stands in stark contrast with lists, which are mutable, and also presents a prime example of comparisons between immutable and mutable data types and structures in Python.

Tuple Literals

Tuple literals are expressions that define tuples and look similar to list literals. You can also separate the items/elements with commas. But instead of square brackets, the tuple literals are enclosed in parentheses.

>>> a = ('table', 'pen', 'book')
>>> type(a)
<class 'tuple'>

You can store any data types or objects as tuple elements and mix them in any order you wish:

>>> (1993, 2022, 1987)
(1993, 2022, 1987)
>>> (1, 'two', 'final', 1.2)
(1, 'two', 'final', 1.2)

You can put other lists or tuples inside a tuple to make complex and deep structures:

>>> ([1, 2, 3], ('table', 'pen', 'book'), 'learnshareit')
([1, 2, 3], ('table', 'pen', 'book'), 'learnshareit')

Here is a little quirk. If your literal only features one element and you don’t provide any comma, it won’t produce a tuple even though it looks like a valid tuple literal.

>>> a = ('learnshareit')
>>> b = (1)
>>> type(a)
<class 'str'>
>>> type(b)
<class 'int'>

To get a tuple, don’t omit the trailing comma following the single element in your literal:

>>> a = ('learnshareit',)
>>> b = (1,)
>>> type(a)
<class 'tuple'>
>>> type(b)
<class 'tuple'>

On top of that, you don’t actually need the parentheses to define a tuple. What makes a literal a tuple is the comma, not the parentheses. You only need the parentheses to prevent syntactic ambiguity or with empty tuples.

Just follow your final element with a comma, and Python will treat it as a tuple literal and add the parentheses for you:

>>> a = 'learnshareit',
>>> a
('learnshareit',)
>>> b = 1, 2, 3,
>>> b
(1, 2, 3)

However, we don’t recommend this because this practice can reduce the readability and consistency of your code. Omitting the parentheses also doesn’t help you pass a tuple as an argument to a function:

>>> print(1, 2, 3,)
1 2 3
>>> print((1, 2, 3))
(1, 2, 3)
>>> type('learnshareit',)
<class 'str'>
>>> type(('learnshareit',))
<class 'tuple'>

tuple()

The tuple() constructor creates a tuple by using the elements and their orders from an iterable. This can be a sequence or any container or object that supports iteration.

These examples illustrate how you can build tuples from strings or lists:

>>> tuple('python')
('p', 'y', 't', 'h', 'o', 'n')
>>> tuple([1999, 2003, 2008])
(1999, 2003, 2008)

The constructor will return an empty tuple when no object is given.

Access Elements Of A Tuple

Tuples also have zero-based order like lists. You can access elements of a tuple by using indexes within square brackets:

>>> a = ('table', 'pen', 'book')
>>> a[1]
'pen'

Slicing also works with tuples. By using a starting index (and an optional ending index as well as an optional step parameter), you can extract a smaller tuple containing consecutive elements in the original tuple:

>>> a[1:]
('pen', 'book')

Tuple Packing And Unpacking

Let’s recall how we can create a tuple without using parentheses:

>>> a = 'table', 'pen', 'book'

This process is known as tuple packing in Python. The statement above has ‘packed’ three string values into the tuple a. There is a reverse operation called tuple unpacking. It can come in handy in your code.

Tuple unpacking allows you to assign multiple variables at the same time:

>>> a
('table', 'pen', 'book')
>>> x, y, z = a
>>> print(x)
table
>>> print(y)
pen
>>> print(z)
book

This operation works with other types of sequences as well. You will have to ensure there are as many elements in the tuple as there are variables on the left side of the equal sign.

You can take advantage of this feature and exchange values between variables in a single statement without using temporary variables:

>>> a = 'python'
>>> b = 'java'
>>> a, b = b, a
>>> print(a)
java
>>> print(b)
python

The right side of the statement creates a tuple under the hood, which is then unpacked into the two variables on the left side.

Loop Through A Tuple

You can iterate through a tuple just as with any other sequence in Python:

>>> a = (1, 2, 3, 4)
>>> for i in a:
...     print(i)
... 
1
2
3
4

Tuple Operations And Methods

Tuples support all the common sequence operations. This is how you can find the length of a tuple, check if any item has the value you want, join two tuples, and duplicate items.

>>> a = (1, 2, 3, 4)
>>> len(a)
4
>>> 2 in a
True
>>> a + (5, 6)
(1, 2, 3, 4, 5, 6)
>>> a * 2
(1, 2, 3, 4, 1, 2, 3, 4)

Tuple comparisons work much like those of Python lists.

>>> a = (1, 2)
>>> a == (1, 2)
True
>>> a <= (1, 2, 3)
True
>>> a >= (1, 2, 3)
False

Tuples have no extend(), append(), pop(), or remove() method. They are immutable, and you can’t add or remove elements from them. In fact, any method that modifies a tuple is impossible to implement.

You still have other methods like count(), which return the number of occurrences of a given element:

>>> a = tuple('learnshareit')
>>> a.count('a')
2

The index() method returns the index of the first element that matches a given value:

>>> a = tuple('learnshareit')
>>> a.index('a')
2

You can use the optional start and end indexes to narrow down the search portion within the tuple. For example, this tells index() to only look for ‘a’ from the fourth to the eight elements:

>>> a.index('a', 4, 9)
7

Tutorials

Summary

Python tuples are ordered sequences like lists. However, they are immutable, and you can’t change them in any way. Tuples are a nice choice when you want an effective collection to store items of different data types.

Leave a Reply

Your email address will not be published. Required fields are marked *