KDnuggets Home » News » 2019 » Nov » Tutorials, Overviews » Python Tuples and Tuple Methods ( 19:n45 )

Python Tuples and Tuple Methods


Brush up on your Python basics with this post on creating, using, and manipulating tuples.



By Michael Galarnyk, Data Scientist

Tuples are an ordered sequences of items, just like lists. The main difference between tuples and lists is that tuples cannot be changed (immutable) unlike lists which can (mutable).

 

Initialize a Tuple

 
There are two ways to initialize an empty tuple. You can initialize an empty tuple by having () with no values in them.

# Way 1
emptyTuple = ()


You can also initialize an empty tuple by using the tuple function.

# Way 2
emptyTuple = tuple()


A tuple with values can be initialized by making a sequence of values separated by commas.

# way 1
z = (3, 7, 4, 2)# way 2 (tuples can also can be created without parenthesis)
z = 3, 7, 4, 2


Figure

You can initialize a tuple with or without parenthesis

 

It is important to keep in mind that if you want to create a tuple containing only one value, you need a trailing comma after your item.

# tuple with one value
tup1 = ('Michael',)# tuple with one value
tup2 = 'Michael',# This is a string, NOT a tuple.
notTuple = ('Michael')


 

Accessing Values in Tuples

 

Figure

You can initialize a tuple with or without without parenthesis

 

Each value in a tuple has an assigned index value. It is important to note that python is a zero indexed based language. All this means is that the first value in the tuple is at index 0.

# Initialize a tuple
z = (3, 7, 4, 2)# Access the first item of a tuple at index 0
print(z[0])


Figure

Output of accessing the item at index 0.

 

Python also supports negative indexing. Negative indexing starts from the end of the tuple. It can sometimes be more convenient to use negative indexing to get the last item in a tuple because you don’t have to know the length of a tuple to access the last item.

# print last item in the tuple
print(z[-1])


Figure

Output of accessing the last item in the tuple

 

As a reminder, you could also access the same item using positive indexes (as seen below).

Figure

Alternative way of accessing the last item in the tuple z

 

 

Tuple slices

 
Slice operations return a new tuple containing the requested items. Slices are good for getting a subset of values in your tuple. For the example code below, it will return a tuple with the items from index 0 up to and not including index 2.

Figure

First index is inclusive (before the :) and last (after the :) is not

 

# Initialize a tuple
z = (3, 7, 4, 2)# first index is inclusive (before the :) and last (after the :) is not.
print(z[0:2])


Figure

Slice of a tuple syntax

 

# everything up to but not including index 3
print(z[:3])


Figure

Everything up to but not including index 3

 

You can even make slices with negative indexes.

print(z[-4:-1])


 

Tuples are Immutable

 
Tuples are immutable which means that after initializing a tuple, it is impossible to update individual items in a tuple. As you can see in the code below, you cannot update or change the values of tuple items (this is different from Python Lists which are mutable).

z = (3, 7, 4, 2)z[1] = "fish"


Even though tuples are immutable, it is possible to take portions of existing tuples to create new tuples as the following example demonstrates.

# Initialize tuple
tup1 = ('Python', 'SQL')# Initialize another Tuple
tup2 = ('R',)# Create new tuple based on existing tuples
new_tuple = tup1 + tup2;
print(new_tuple)


 

Tuple Methods

 

Before starting this section, let’s first initialize a tuple.

# Initialize a tuple
animals = ('lama', 'sheep', 'lama', 48)


 

index method

 
The index method returns the first index at which a value occurs.

print(animals.index('lama'))


 

count method

 
The count method returns the number of times a value occurs in a tuple.

print(animals.count('lama'))


Figure

The string ‘lama’ appears twice in the tuple animals

 

 

Iterate through a Tuple

 
You can iterate through the items of a tuple by using a for loop.

for item in ('lama', 'sheep', 'lama', 48):
   print(item)


 

Tuple Unpacking

 
Tuples are useful for sequence unpacking.

x, y = (7, 10);
print("Value of x is {}, the value of y is {}.".format(x, y))


 

Enumerate

 
The enumerate function returns a tuple containing a count for every iteration (from start which defaults to 0) and the values obtained from iterating over a sequence:

friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):
    print(index,friend)


 

Advantages of Tuples over Lists

 


Quick video on this section

 

Lists and tuples are standard Python data types that store values in a sequence. Atuple is immutable whereas a list is mutable. Here are some other advantages of tuples over lists (partially from Stack Overflow)

  • Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list. The performance difference can be partially measured using the timeit library which allows you to time your Python code. The code below runs the code for each approach 1 million times and outputs the overall time it took in seconds.
import timeitprint(timeit.timeit('x=(1,2,3,4,5,6,7,8,9,10,11,12)', number=1000000))print(timeit.timeit('x=[1,2,3,4,5,6,7,8,9,10,11,12]', number=1000000))


  • Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable (you can learn about dictionaries here).

  • Tuples can be used as values in sets whereas lists can not (you can learn more about sets here)

 

Conclusion

 
If you have any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter. Next post reviews Python Dictionaries and Dictionary Methods. If you want to learn how to utilize the Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. Here is a free preview video.

 

 
Bio: Michael Galarnyk is a Data Scientist and Corporate Trainer. He currently works at Scripps Translational Research Institute. You can find him on Twitter (https://twitter.com/GalarnykMichael), Medium (https://medium.com/@GalarnykMichael), and GitHub (https://github.com/mGalarnyk).

Original. Reposted with permission.

Related:


Sign Up

By subscribing you accept KDnuggets Privacy Policy