Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Thursday, 10 November 2016

Introduction to Python Tuple

Python Tuple- Hello readers! In some of recent articles, we have been discussing on built-in data structures (or data types) in Python. We have already covered Python Strings, Python Lists and Python Dictionaries. In this article, we introduce you to another Python built-in data structure - Python Tuple. If you remember how Python lists behave, you can easily understand the behavior of Python Tuple, as they work in pretty similar way. They have a few dissimilar properties though, which we will be learning as we go through this article. Let's start!

python-tuple

Like Python lists, Python tuples are ordered collection of Python objects (strings, lists, dictionaries, tuples, numbers, etc), separated by a comma (,) and enclosed in parenthesis (( )). I emphasized the word 'ordered', as every element in a tuple (again, like lists) is associated with a positional parameter, which we call as - index or offset. As a tuple is made up of zero or more Python objects, it is also a Python object and it's an instance of Python built-in tuple class. To know more about tuples, lets create one!

Creating Tuples

The easiest tuple to create is the empty tuple - no elements in the tuple. To create an empty tuple, we do not put any elements in the parenthesis. This is one way and another was is to use Python built-in tuple() function, which when called with no arguments, returns an empty tuple.

>>> myTuple = ()
>>> myTuple
()

>>> myTuple = tuple()
>>> myTuple
()

Success! We now move ahead an create an non-empty tuple. We just need to put bunch of Python objects we have studied by now, within the parenthesis.

# A tuple of Integers
>>> myTuple = (1, 4, 9, 16, 25)
>>> myTuple
(1, 4, 9, 16, 25)

# A tuple of Strings
>>> myTuple = ('One', 'Four', 'Nine', 'Sixteen', 'Twenty Five')
>>> myTuple
('One', 'Four', 'Nine', 'Sixteen', 'Twenty Five')

# A tuple of Lists
>>> myTuple = (['One', 'Four'], ['Nine', 'Sixteen'], ['Twenty Five'])
>>> myTuple
(['One', 'Four'], ['Nine', 'Sixteen'], ['Twenty Five'])

# A tuple of Dictionaries
>>> myTuple = ({'One' : 1, 'Four' : 2}, {'Nine' : 3, 'Sixteen' : 4, 'Twenty Five': 5})
>>> myTuple
({'Four': 2, 'One': 1}, {'Sixteen': 4, 'Nine': 3, 'Twenty Five': 5})

# A tuple of Tuples
>>> myTuple = ((1, 'One'), (2, 'Four'), (3, 'Nine'), (4, 'Sixteen'), (5, 'Twenty Five'))
>>> myTuple
((1, 'One'), (2, 'Four'), (3, 'Nine'), (4, 'Sixteen'), (5, 'Twenty Five'))

# A mixed tuple
>>> myTuple = ({1 : 'One', 2 : 'Four'}, [3, 'Nine', 4, 'Sixteen'], 5, 'Twenty Five')
>>> myTuple
({1: 'One', 2: 'Four'}, [3, 'Nine', 4, 'Sixteen'], 5, 'Twenty Five')

Note : One very important thing to remember is that, a tuple with only one item can be created as (item,) and not (item). A comma must be mentioned or it will not be considered as a tuple type.

# Invalid one-item tuples
>>> myTuple = ('item')
>>> type(myTuple)
<type 'str'>

>>> myTuple = (101)
>>> type(myTuple)
<type 'int'>

# Valid one-item tuples
>>> myTuple = ('item',)
>>> type(myTuple)
<type 'tuple'>

>>> myTuple = (101,)
>>> type(myTuple)
<type 'tuple'>

As mentioned earlier, another way to create a tuple is using tuple() built-in Python function. This function expects an iterable as an argument and returns a tuple of elements in that iterable.

# String as the iterable
>>> myTuple = tuple('CodeNinjaDotIn')
>>> myTuple
('C', 'o', 'd', 'e', 'N', 'i', 'n', 'j', 'a', 'D', 'o', 't', 'I', 'n')

# List as the iterable
>>> myTuple = tuple(['Code', 'Ninja', '.', 'In'])
>>> myTuple
('Code', 'Ninja', '.', 'In')

# Dictionary as the iterable
>>> myTuple = tuple({1 : 'One', 2 : 'Four', 3 : 'Nine'})
>>> myTuple
(1, 2, 3)

Tuple Indexing and Accessing Tuple Items

Tuples being the Ordered collection of Python objects, any tuple item can be accessed using it's index in the tuple, the same way with which list items are accessed. As you might know by now that, indexing starts from zero, moving from left to right, in a tuple. So, the first tuple item can be accessed as tupleName[0], second tuple item as tupleName[1], and so on. As in lists, we have negative indexing in tuples, such that tuple items can be accessed in reverse order (right to left), using negative indices. Thus, last tuple item can be accessed as tupleName[-1] and last but one item as tupleName[-2]. This feature is very useful when we have very very long tuples. We also have Python built-in function len() to determine the length of a tuple.

# We create a mixed tuple
>>> myTuple = ({1 : 'One', 2 : 'Four'}, [3, 'Nine', 4, 'Sixteen'], (5, 'Twenty Five'), 6, 'Thirty Six')
>>> myTuple
({1: 'One', 2: 'Four'}, [3, 'Nine', 4, 'Sixteen'], (5, 'Twenty Five'), 6, 'Thirty Six')

# Accessing item at index '0' = 1st item
>>> myTuple[0]
{1: 'One', 2: 'Four'}

# Accessing item at index '2' = 3rd item
>>> myTuple[2]
(5, 'Twenty Five')

# Accessing item at index '1' of item at index '2'
>>> myTuple[2][1]
'Twenty Five'

# Accessing item at index '1' of item at index '2'
>>> myTuple[0][1]
'One'

# Accessing item at index '-1' = Last item
>>> myTuple[-1]
'Thirty Six'

# Last item is a String - Let's slice it
>>> myTuple[-1][-3:]
'Six'

# Negative indexing - another example
>>> myTuple[-3]
(5, 'Twenty Five')

# Some complex slicing
>>> myTuple[-3][1][-4:]
'Five'

# Size of the tuple using 'len()' function
>>> len(myTuple)
5

Concatenation and Repetition

Like strings and lists, we can concatenate two or more tuples, using + operator, to produce an another tuple type. Needless to mention here that, the two objects we are concatenating need to be of same type, or TypeError will be displayed.

>>> myTuple1 = (1, 2, 3, 4)
>>> myTuple2 = ('One', 'Four', 'Nine', 'Sixteen')
>>> myTuple3 = (5, 'Twenty Five')

>>> myTuple1 + myTuple2 + myTuple3
(1, 2, 3, 4, 'One', 'Four', 'Nine', 'Sixteen', 5, 'Twenty Five')
>>> type(myTuple1 + myTuple2 + myTuple3)
<type 'tuple'>

We have another operator * with which we can repeat an instance of a Python tuple, to produce a tuple of repeated sequence of tuple items. So, in order to create a tuple from repetition of another tuple, we can use the syntax tuple_name * N, where N is the number of times the sequence has to be repeated.

>>> (1, 'Two', 3, 'Four') * 4
(1, 'Two', 3, 'Four', 1, 'Two', 3, 'Four', 1, 'Two', 3, 'Four', 1, 'Two', 3, 'Four')

>>> myTuple = (1, 'Two', 3, 'Four')
>>> myTuple * 4
(1, 'Two', 3, 'Four', 1, 'Two', 3, 'Four', 1, 'Two', 3, 'Four', 1, 'Two', 3, 'Four')
>>> type(myTuple * 4)
<type 'tuple'>

Slicing

With Slicing, we can cut-out a part of tuple and process it. Similar to slicing in strings and lists, we need to mention here following offsets- START indicating where should the slicing start from and END indicating where should slicing stop at (this won't include the element at index END). The default value of START is '0', while the default value of END is the index of last item of the tuple. When it comes to slicing, there is another optional parameter STEP, which will get us every STEPth element (i.e. skipping STEP-1 elements), starting from element at the index START till but not including element at index END. The default value of this parameter is '1'. So, the syntax used for slicing a tuple can be put as - tuple_name[START : END : STEP]

>>> myTuple = tuple(range(10))
>>> myTuple
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# Tuple slice starting from the item at index '3' till last item
>>> myTuple[3:]
(3, 4, 5, 6, 7, 8, 9)

# Tuple slice starting from beginning till but not including item at index '8'
>>> myTuple[:8]
(0, 1, 2, 3, 4, 5, 6, 7)

# Tuple slice starting from item at index '3' till but not including item at index '8'
>>> myTuple[3:8]
(3, 4, 5, 6, 7)

# A complete slice
>>> myTuple[:]
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# A tuple slice with step 2
>>> myTuple[3:8:2]
(3, 5, 7)

# Tuple reversal using STEP = -1
>>> myTuple[::-1]
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

# A reversed tuple containing every other item
>>> myTuple[::-2]
(9, 7, 5, 3, 1)

Tuples are not 'Mutable'

Till now, we have studied different operations associated with Python tuples, but never tried to modify one. Let us try to add or modify the value of a tuple item, to check whether we are allowed to do so.

>>> myTuple = tuple(range(6))
>>> myTuple
(0, 1, 2, 3, 4, 5)

# Modifying a Tuple item
>>> myTuple[3] = 'Three'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# Adding an item to a tuple
>>> myTuple[7] = 'Six'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# Deleting a tuple item
>>> del myTuple[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

No! We are not allowed to change the tuple items. So, Tuples are immutable Python objects.

With this, we have come to an end of this article. In this article, we have had a brief introduction to Python tuples and studied different operations we can perform on them. In the next article, we would be learning the methods associated with Python tuples. Please share your views and opinions in the comment section below and stay tuned for more exciting articles. Thank you.

This article is originally published at www.codeninja.in - Python Tuples

0 comments:

Post a Comment