Best post on tuple datatype in python – 1

Tuple Datatype in Python

Python supports many simple and compound datatypes.

Few data types like list, dictionary are mutable and others like string datatype, tuple are immutable.

Mutable datatypes means changes can be done and are reflected in same variable.

Immutable datatypes means changes can be done but not in same variable.

 

Tuple is similar to list datatype but only difference between them is that list is mutable and tuple is immutable data type. We can change the contents of list even after assigning values but we cannot change the contents of tuple once assigned with its values.

An empty tuple represents zero or null value.

A tuple datatype can be defined with use of parentheses () containing values separated with comma ” , “.

Each value is termed to be an item of the tuple.

Initializing a tuple

We can initialize a tuple in following ways:

  • With the use of empty parentheses we can define an empty tuple : ()
  • We can use a comma after the value to create single value tuple : (1,)
  • We can create multi value tuple using comma separation : (1,2,3)
  • We can use built in  function to create tuple or to convert other datatype to tuple : tuple() or tuple(iterable)

Examples to create tuple with parenthesis:

>>> tup1=() #to create empty tuple
>>> tup1
()
>>> tup2=(1,2,3)
>>> tup2
(1, 2, 3)
>>> tup2=(1,) # single value tuple
>>> tup2
(1,)
>>> tup3=(1) #this cannot be a single value tuple its an integer
>>> tup3
1
>>> type(tup2)
<class 'tuple'>
>>> type(tup3)
<class 'int'>
>>> tup4=('a',25,9.36,'python')
>>> type(tup4)
<class 'tuple'>

Examples to create tuple without parenthesis:

>>> z='a','o','p'
>>> type(z)
<class 'tuple'>
>>> x=1,2,3,'itvoyagers'
>>> type(x)
<class 'tuple'>

NOTE: We cannot create a single value tuple without giving a trailing comma after your single value.

Accessing a tuple

A tuple can be accessed using square brackets [].

It is similar to slicing a list or string.

Index position starts with 0 till n-1 where n is the total length of the tuple.

For backward tracking we can uses negative indexing like -1,-2 etc.

This operation is just used to access the values present in tuple and have no effect on actual tuple.

Example

>>> itv=(1,2,3,4,5,6)
>>> itv[2]
3
>>> itv[2:5]
(3, 4, 5)
>>> itv[-1]
6
>>> itv[6:1:-1]
(6, 5, 4, 3)
>>>

Example:

>>> itv=(1,2,3,4,5,6)
>>> itv[6]
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
itv[6]
IndexError: tuple index out of range
>>> itv[2.8]
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
itv[2.8]
TypeError: tuple indices must be integers, not float
>>>

From above example it is clear that we cannot use a float value as index. An index should always be an integer and last value of index will always be n-1 if total length is n.

len function or len()

Python provides a built-in function called as len() to calculate number of items in a tuple or simply we can say length of a tuple.

 

Example:

>>> itv=(1,2,3,4,5,6)
>>> len(itv)
6
>>> x=1,2,3,'itvoyagers'
>>> len(x)
4
>>> p=(100,) # single value tuple
>>> len(p)
1

Negative Indexing

We can use negative indexing for tuple datatype which will help us to count backward from the end of the tuple.

If we use letters[-1] it will give output as ‘s’.

Negative indexing starts with -1 and not 0 so it ends with -n i.e total length of data.

So if we give negative index as n+1 that is more than total length it will raise an error.

>>> letters=('i','t','v','o','y','a','g','e','r','s')
>>> letters[-1]
's'
>>> letters[-2]
'r'
>>> letters[-10]
'i'
>>> letters[-11]
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
letters[-11]
IndexError: tuple index out of range
>>>

In negative indices, index begins with -1 and not 0 so last value of indexing will be -10 in our example and not -9.

Traversing tuple using for loop

Traversing is a process of moving in an iterable and locating values from index position.

In this case our iterable is of type tuple and loop used is for loop.

>>> itv=(1,2,3,4,5,6)
>>> for i in itv:
print(i**4)

Output:

1
16
81
256
625
1296

Tuple slicing

A tuple datatype can be sliced using [ : ] .

Syntax:

[start : end : step]

This provide start and end value.

Sometimes a step value is also mentioned after end value using colon separation.

In below example we will see multiple outputs or multiple ways to slice a tuple datatype.

 

Example:

#tuple slicing
demo_tuple = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)
print('demo_tuple[0:5]',demo_tuple[0:5])
print('demo_tuple[9:12]',demo_tuple[9:12])
print('demo_tuple[5:12]',demo_tuple[5:12])
print('demo_tuple[:3]',demo_tuple[:3])
print('demo_tuple[3:]',demo_tuple[3:])
print('demo_tuple[3:3]',demo_tuple[3:3])
print('demo_tuple[:]',demo_tuple[:])
print('demo_tuple[0]',demo_tuple[0])
print('demo_tuple[10]',demo_tuple[10])
print('demo_tuple[5]',demo_tuple[5])
print('demo_tuple[5:14:2]',demo_tuple[5:14:2])
print('demo_tuple[5::2]',demo_tuple[5::2])
print('demo_tuple[:14:2]',demo_tuple[:14:2])
print('demo_tuple[5:1:-2]',demo_tuple[5:1:-2])
print('demo_tuple[5:1:-1]',demo_tuple[5:1:-1])
print('demo_tuple[::]',demo_tuple[::])

Output:

tuple datatype
slicing of tuple datatype

Deleting a tuple

We cannot delete or remove single or multiple elements / items form the tuple as tuple is immutable and we cannot update or delete its elements individually.

Example:

>>> itv=(1,2,3,4,5,6)
>>> del itv[2]
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
del itv[2]
TypeError: 'tuple' object doesn't support item deletion
>>> del itv[2:5]
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
del itv[2:5]
TypeError: 'tuple' object does not support item deletion
>>> del itv
>>> itv
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
itv
NameError: name 'itv' is not defined

In above example it is clear that entire tuple can be deleted but not parts of it.

Other python related post

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon…….

Other advance python related post

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in ‘re’ module(Part I)- Match vs Search
Functions in ‘re’ module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
Best post on Select Query to Search & Read: Python + MySQL-4
Best post on Update query and Delete query : Python + MySQL-4
New posts coming soon…….
We are aiming to explain all concepts of Python in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment