Python Tuples Tutorial

Contents show

Python Tuples tutorial

Python Tuples Tutorial
Python Tuples Tutorial

Python Tuples Tutorial : In this tutorial, you will learn Python Tuples with Examples and practice programs.

INTRODUCTION


The Python Tuples are sequences that are used to store a tuple of values of any type. You have learnt in earlier chapters that Python tuples are immutable i.e., you cannot change the elements of a tuple in place; Python will create a fresh tuple when you make changes to an element of a tuple. Tuple is a type of sequence like strings and lists but it differs from them in the way that lists are mutable but strings and tuples are immutable.


Python Tuples


The Tuples are depicted through parentheses i.e., round brackets, e.g., following are some tuples in Python :

( )                                  # tuple with no member, empty tuple
(7, )                               # tuple with one member
(1, 2, 3)                         # tuple of integers
(1, 2.5, 3.7, 9)              # tuples of numbers(integers and floating point)
('a', 'b', 'c')                   # tuples of characters
('a', 1, 'b', 3.5, 'zero')   #tuples of mixed value types
('One', 'Two', 'Three')     # tuple of strings

Tuples are immutable sequences i.e., you cannot change elements of a tuple in place.


1. Creating Python Tuples


To create a tuple, put a number of expressions, separated by commasin parentheses. That is, to create a tuple you can write in the form given below :
T = ( )
T = (value, …)
This construct is known as a tuple display construct.


Creating Empty Python Tuple


The empty tuple is ( ). You can also create an empty tuple as :
T = tuple( )


Creating Single Element Python Tuple


Making a tuple with a single element is tricky because if you just give a single element in round brackets, Python considers it a value only, e.g.,

>>> t = (1)
>>> t
1             <---- (1) was treated as an integer expression, hence t stores an integer 1, not a tuple

To construct a tuple with one element just add a comma after the single element as shown below :

>>> t = 3,               <--- To create a one-element tuple, make sure to add comma at the end
>>> t
(3, )                       <--- Now t stores a tuples, not integer.

Creating Tuples from Existing Sequences


You can also use the built-in tuple type object (tuple( ) ) to create tuples from sequences as per the syntax given below :

T = tuple(<sequence>)

where <sequence> can be any kind of sequence object including strings, lists and tuples.


Consider following examples :

>>> t1 = tuple('hello')
>>> t1
('h', 'e', 'l', 'l', 'o')
>>> L = ['w', 'e', 'r', 't', 'y']
>>> t2 = tuple(L)
>>> t2
('w', 'e', 'r', 't', 'y')

Creating Tuple from Keyboard Input


you can use this method of creating tuples of single characters or single digits via keyboard input.


Consider the code below :

t1 = tuple(input('Enter tuple element :'))
Enter tuple elements : 234567
>>> t1
('2', '3', '4', '5', '6', '7')

But most commonly used method to input tuples is eval(input( )) as shown below :

tuple = eval(input("Enter tuple to added :"))
print("Tuple you entered :", tuple)

when you execute it, it will work somewhat like :

Enter tuple to be added : (2, 4, "a", "hjkj1", [3, 4])
Tuple you entered : (2, 4, "a", "hjkj1", [3, 4])

2. Python Tuple vs List


Tuples and Lists are very similar yet different. This section is going to talk about the same.


Similarity between Tuples and Lists


Tuples are similar to lists in following ways :

  • Length

Function len(T) returns the number of items (count) in the tuple T.

  • Indexing and Slicing


T[i] returns the item at index i (the first item has index 0), and T[i: j] returns a new tuple, containing the objects between i and j.

  • Membership operators

Both ‘in’ and ‘not in’ operators work on Tuples also. That is, in tells if an element is present in the tuple or not and not in does the opposite.

  • Concatenation and Replication operators + and *


The + operator adds one tuple to the end of another. The * operator repeats a tuple.

  • Accessing Individuals Elements


The individual elements of a tuple are accessed through their indexes given in square brackets. Consider the following examples :

 >>> vowels = ('a', 'e', 'i', 'o', 'u')
>>> vowels[4]
'u'
>>> vowels[-1]
'u'

Difference between Tuples and Lists


Tuples are not mutable, while lists are. You cannot change individual elements of a tuple in place, but lists allow you to do so. That is, following statements is fully valid for lists(BUT not for tuples).


If we have a list L and a Tuple T, then

L[i] = element                   # is valid

is VALID for Lists. BUT

T[i] = element                 # is invalid

is INVALID for tuples as you cannot perform item-assignment in immutable types.


3. Tuple Operations


In this section, we shall talk most common tuple operations, briefly.


1. Traversing a Tuple

Traversing a tuple means accessing and processing each element of it. The for loop makes it easy to traverse or loop over the items in a tuple, as per following syntax :

for <item> in <Tuple> :
      process each item here

For example, following loop shows each item of a tuple T in separate lines :

T = ('p', 'u', 'r', 'e')
for a in T :
      print(T[a])

The above loop will produce result as :

p
u
r
e

2. Joining Tuples


The + operator, the concatenation operator, when used with two tuples, joins two tuples.


Consider the example given below :

>>> tpl1 = (1, 3, 5)
>>> tpl2 = (6, 7, 8)
>>> tpl1 + tpl2
(1, 3, 5, 6, 7, 8)

Important

Sometimes you need to concatenate a tuple (say tpl) with another tuple containing only one element. In that case, if you write statement like :

tpl + (3)

Python will return an error like :

TypeError : can only concatenate tuple (not “int”) to tuple

The reason for above error is : a single value in ( ) is treated as single value not as tuple. That is, expressions (3) and (‘a’) are integer and and string respectively but (3, ) and (‘a’, ) are single element tuples. Thus following expression won’t give any error :

tpl + (3, )

Python Tuples Tutorial

3. Repeating or Replicating Tuples


Like strings and lists, you can use * operator to replicate a tuple specified number of times, e.g.,

>>> tpl1 * 3
(1, 3, 5, 1, 3, 5, 1, 3, 5)

Like strings and lists, you can only use an integer with a * operator when trying to replicate a tuple.


4. Slicing the Tuples


Tuple slices, like list-slices or string slices are the sub part of the tuple extracted out. You can use indexes of tuple elements to create tuple slices as per following format :

seq = T[start : stop]

Recall that index on last limit is not included in the tuple slice. Consider the following example :

>>> tpl1 = (10, 12, 14, 20, 22, 24, 30, 32, 34)
>>> seq = tpl[ 3:-3]
>>> seq
(20, 22, 24)

If you want to extract, not consecutive but every other element of the tuple, there is a way out the slice steps. The slice steps are used as per following format :

seq = T[start : stop : step]

Consider some examples to understand this.

>>> tpl1
(10, 12, 14, 20, 22, 24, 30, 32, 34)
>>> tpl[ 0 : 10 : 2]
(10, 14, 22, 30, 34)
>>> tpl[ 2 : 10 : 3]
(14, 24, 34)
>>> tpl[ :: 3]
(10, 20, 30)

Unpacking Tuples


Creating a tuple from a set of values is called packing and its reverse, i.e., creating individual values from a tuple’s elements is called unpacking.
Unpacking is done as per syntax :

<variable>, <variable2>, <variable3>, ... = t

where the number of variables in the left side of assignment must match the number of elements in the tuple.


For example, if we have a tuple as :


t = (1, 2, ‘A’, ‘B’)
The length of above tuple t is 4 as there are four elements in it. Now to unpack it, we can write :

w, x, y, z = t
print(w, "-", x, "-", y, "-", z)

The output will be :

1-2-A-B

4. Tuple Functions and Methods

1. The len( ) method


This method returns length of the tuple, i.e., the count of element in the tuple.
syntax :

len(<tuple>)

Example :

>>> employee = ('john', 10000, 24, 'sales')
>>> len(employee)
4                      The len( ) returns the count of elements in the tuple

2. The max( ) method


This method returns the element from the tuple having maximum value.
syntax :

max(<tuple>)

Example :

>>> tpl = (10, 12, 14, 20, 22, 24, 30, 32, 34)
>>> max(tpl)
34                  Maximum value from tuple tpl is returned

3. The min( ) method


This method returns the element from the tuple having minimum value.
syntax :

min(<tuple>)

Example :

>>> tpl = (10, 12, 14, 20, 22, 24, 30, 32, 34)
>>> minn(tpl)
10                     Maximum value from tuple tpl is returned

Note :


Like max( ), for min( ) to work the elements of tuple should be of same type.

4. The index( ) method


It returns the index of an existing element of a tuple.
syntax :

<tuplename>.index(<item>)

Example :

>>> t1 = [3, 4, 5, 6.0]
>>> t1.index(5)
2

5. The count( ) function


The count( ) method returns the count of a member element/object in a given sequence (list/tuple).
syntax :

<sequence name>.count(<object>)

Example :

>>> t1 = (2, 4, 2, 5, 7, 4, 8, 9, 9, 11, 7, 2)
>>> t1.count(2)
3                 There are 3 occurences of element 2 in given tuple, hence count( ) return 3 here

6. The tuple( ) method


This method is actually constructor method that can be used to create tuples from different types of values.
syntax :

tuple(<sequence>)

1. Creating empty tuple

>>> tuple( )
( )

2.Creating a tuple from a list

>>> t = tuple([1, 2, 3])
>>> t
(1, 2, 3)

3. Creating tuple from a string

>>> t = tuple("abc")
>>> t
('a', 'b', 'c')

4. creating a tuple from keys of a dictionary

>>> t1 = tuple({1: "A", 2: "B"})
>>> t1
(1, 2)

Python Tuples Tutorial video

Python Tuples Tutorial video Credit : Telusko

Read More :

Python Tuples Practice Questions

Python Tuples

FAQ :-

Q 1. What are Python Tuples ?

Ans. Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

Q 2. What is difference between tuple and list in python?

Ans. Conclusion. We can conclude that although both lists and tuples are data structures in Python, there are remarkable differences between the two, with the main difference being that lists are mutable while tuples are immutable. A list has a variable size while a tuple has a fixed size.

Q 3. Can you add tuples in Python?

Ans. You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuplesYou can only add or combine same data types.

Q 4. Why are tuples immutable?

Ans. Tuples support the same sequence operations as strings. The index operator selects an element from a tuple. So like strings, tuples are immutable. Once Python has created a tuple in memory, it cannot be changed.

Q 5. Why does Python have both lists and tuples?

Ans. The Key Difference between a List and a Tuple. The main difference between lists and tuples is the fact that lists are mutable whereas tuples are immutable. … A mutable data type means that a python object of this type can be modified. An immutable object can’t.

Python Tuples Tutorial

You may also like...

Leave a Reply

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