8 Tuples
8 Tuples
Tuples
A Tuple is a collection of Python objects separated by commas.
A tuple is similar to a list in terms of indexing, nested objects
and repetition.
A tuple is immutable.
Elements are written within ( )
empty_tuple = () Output
print (empty_tuple)
# Usual way ()
t1 = ('python', 'coders') ('python', 'coders')
print(t1) ('python', 'coders')
# Another way without ()
t1 = 'python', 'coders'
print(t1)
Concatenation & Nesting of Tuples
Concatenation of 2 tuples can be done by using + operator.
# Concatenation of 2 tuples
t2 = (10, 20, 30, 40) (10, 20, 30, 40, 'python', 'coding')
t3 = ('python', 'coding')
t4=t2+t3
print(t4)
Output
Traceback (most recent call last):
File "D:\SBMP\SUBJECTS\Python\Progs\tuples\tuple1.py", line 25, in <module>
tuple1[0] = 40
TypeError: 'tuple' object does not support item assignment
Slicing in Tuples
Slicing can be done same as List
Output
('keyboard', 'printer', 'monitor')
('monitor', 'printer', 'keyboard', 'mouse')
('printer', 'monitor')
“
We can delete a tuple using del i.e. del t1
Converting Lists into Tuples
tuple() method converts list into tuples.
Output
(0, 1, 2)
('t', 'u', 'p', 'l', 'e')
“
tuple() method takes a single parameter which may be a list, string, set or even a
dictionary( only keys are taken as elements) and converts them to a tuple.
8
Tuple Methods
index() : returns index of the given element from the
tuple.
# Initialize a tuple
cities = ('Mumbai','Rajkot','Pune','Nagpur')
print(cities.index('Pune'))
print(cities.index('Baroda'))
Output
2
Traceback (most recent call last):
File "D:\SBMP\SUBJECTS\Python\Progs\tuples\tuple_methods.py", line 8, in <module>
print(cities.index('Baroda'))
ValueError: tuple.index(x): x not in tuple
Tuple Methods
count() : returns occurrence of given element in the
tuple.
# Initialize a tuple
1
cities = ('Mumbai','Rajkot','Pune','Nagpur') 0
print(cities.count('Pune'))
print(cities.count('Baroda'))
Output
Iterate through a Tuple
Mumbai
Rajkot
#Iterating through tuples
Pune
for item in cities: Nagpur
print(item)
Tuple iteration using Enumerate
Enumerate() returns tuple elements with index and
elements.
languages = ('C', 'JAVA', 'C++','VB','Python','PHP')
for index, language in enumerate(languages):
print((index,language))
(0, 'C')
(1, 'JAVA')
(2, 'C++')
(3, 'VB')
(4, 'Python')
(5, 'PHP')
Other methods
languages = ('C', 'JAVA', 'C++','VB','Python','PHP')
print(max(languages))
print(min(languages))
var=sorted(languages)
print(var)
nt=(1,2,3,4,5)
print(sum(nt))
print(any((1,))) # returns true if any element exists
Output
VB
C
['C', 'C++', 'JAVA', 'PHP', 'Python', 'VB']
15
True
“
○ Tuples are faster than lists. If you’re defining a constant set of values and all
you’re ever going to do with it is iterate through it, use a tuple instead of a list.
13
THANKS!
Any questions?
You can find me at
▸ avanishvishwakarma96@gmail.com