본문으로 건너뛰기

Python Tuples Tutorial

Learn about Python tuples: what they are, how to create them, when to use them, what operations you perform on them and various functions you should know.
· 10분 읽기

AI와 탐험해 보세요

Similar to Python lists, tuples are another standard data type that allows you to store values in a sequence. They might be useful in situations where you might want to share the data with someone but not allow them to manipulate the data. They can however use the data values, but no change is reflected in the original data shared.

In this tutorial, you will see Python tuples in detail:

python tuple tutorial

Be sure to check out DataCamp's Data Types for Data Science course, where you can consolidate and practice your knowledge of data structures such as lists, dictionaries, sets, and many more! Alternatively, also check out this Python Data Structures Tutorial, where you can learn more about the different data structures that Python uses.

Python Tuple

As you already read above, you can use this Python data structure to store a sequence of items that is immutable (or unchangeable) and ordered.

Tuples are initialized with () brackets rather than [] brackets as with lists. That means that, to create one, you simply have to do the following:

cake = ('c','a','k','e')
print(type(cake))
<class 'tuple'>

Remember that the type() is a built-in function that allows you to check the data type of the parameter passed to it.

Tuples can hold both homogeneous as well as heterogeneous values. However, remember that once you declared those values, you cannot change them:

mixed_type = ('C',0,0,'K','I','E')

for i in mixed_type:
    print(i,":",type(i))
C : <class 'str'>
0 : <class 'int'>
0 : <class 'int'>
K : <class 'str'>
I : <class 'str'>
E : <class 'str'>
# Try to change 0 to 'O'
mixed_type[1] = 'O'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-16-dec29c289a95> in <module>()
----> 1 mixed_type[1] = 'O' # Trying to change 0 to 'O'


TypeError: 'tuple' object does not support item assignment

You get this last error message because you can not change the values inside a tuple.

Here is another way of creating a tuple:

numbers_tuple = 1,2,3,4,5
print(type(numbers_tuple))
<class 'tuple'>

Tuples versus Lists

As you might have noticed, tuples are very similar to lists. In fact, you could say that they are immutable lists which means that once a tuple is created you cannot delete or change the values of the items stored in it. You cannot add new values either. Check this out:

numbers_tuple = (1,2,3,4,5)
numbers_list = [1,2,3,4,5]

# Append a number to the tuple
numbers_tuple.append(6)
------------------------------------