Python Code Tuto 4
Python Code Tuto 4
Tuple
1. Tuple is similar to List except that the objects in tuple are immutable which means we cannot
change the elements of a tuple once assigned.
2. When we do not want to change the data over time, tuple is a preferred data type.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
Tuple Creation
[2]: tup1 = () # Empty tuple
[52]: len(tup5)
[52]: 4
[54]: tup5[2][1]
[54]: 100
[9]: 6
Tuple Indexing
[55]: tup2
1
[55]: (10, 30, 60)
[10]: 10
[56]: tup4
[11]: 'one'
[12]: tup4[0][0] # Nested indexing - Access the first character of the first tuple␣
↪element
[12]: 'o'
[13]: 'three'
[57]: tup5
Tuple Slicing
[15]: mytuple = ('one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' ,␣
↪'eight')
[16]: mytuple[0:3] # Return all items from 0th to 3rd index location
[17]: mytuple[2:5] # List all items from 2nd to 5th index location
2
[19]: mytuple[:2] # Return first two items
[22]: 'eight'
[25]: del mytuple[0] # Tuples are immutable which means we can't DELETE tuple items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[25], line 1
----> 1 del mytuple[0]
[26]: mytuple[0] = 1 # Tuples are immutable which means we can't CHANGE tuple items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[26], line 1
----> 1 mytuple[0] = 1
3
Loop Through Tuple
[30]: mytuple = ('one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' ,␣
↪'eight')
[31]: mytuple
one
two
three
four
five
six
seven
eight
(0, 'one')
(1, 'two')
(2, 'three')
(3, 'four')
(4, 'five')
(5, 'six')
(6, 'seven')
(7, 'eight')
Count
[35]: mytuple1 =('one', 'two', 'three', 'four', 'one', 'one', 'two', 'three')
[36]: 3
[37]: 2
[38]: 1
4
Tuple Membership
[39]: mytuple
[60]: True
[41]: False
[45]: 0
[46]: 4
[47]: mytuple1
[48]: 0
5
Sorting
[49]: mytuple2 = (43,67,99,12,6,90,67)
[50]: sorted(mytuple2) # Returns a new sorted list and doesn't change original tuple
[ ]: