Tag Archive Python


Python Tuples

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.

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:

  • You will learn how you can initialize tuples. You will also see the immutable nature of tuples through examples;
  • You’ll also discover how a tuple differs from a Python list;
  • Then, you will see the various tuple operations, such as slicing, multiplying, concatenating, etc.;
  • It is helpful to know some built-in functions with tuples and you will see some important ones in this section.
  • Finally, you’ll see that it is also possible to assign multiple values at once to tuples.

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')
<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:
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
<class 'tuple'>

sumber : https://www.datacamp.com/community/tutorials/python-tuples-tutorial
Contact Us