In [8]:
# Creating a tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple)
('apple', 'banana', 'cherry')
In [23]:
# Creating a tuple using tuple constructor
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
('apple', 'banana', 'cherry')
In [9]:
# Tuples items can be accessed through index, which start from 0
thistuple = ("apple", "banana", "cherry")
print(thistuple)
print(thistuple[0])
print(thistuple[1])
print(thistuple[2])
('apple', 'banana', 'cherry') apple banana cherry
In [10]:
# Tuple is immutable - can't change
thistuple = ("apple", "banana", "cherry")
thistuple[1]="orange"
print(thistuple)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[10], line 4 1 # Tuple is immuatable - can't change 3 thistuple = ("apple", "banana", "cherry") ----> 4 thistuple[1]="orange" 5 print(thistuple) TypeError: 'tuple' object does not support item assignment
In [11]:
# Tuple can have duplicate items
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry')
In [12]:
# Length of a tuple
thistuple = ("apple", "banana", "cherry")
print(len(thistuple)) # return number of itmes
3
In [14]:
# Correct syntax
# To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple
thistuple = ("apple",)
print(type(thistuple))
<class 'tuple'>
In [21]:
# Try to create tuple with one item without comma after item name
# Python will not treat it as a tuple
thistuple=("apple")
print(thistuple)
print(type(thistuple))
apple <class 'str'>
In [22]:
# Tuple items can be of any type even mixted types as well
tuple1 = ("apple", "banana", "cherry") # str types
tuple2 = (1, 5, 7, 9, 3) # number type
tuple3 = (True, False, False) # boolean type
tuple4 =( True , 2,3,"Hello",2.5,0 , 1 ) # mixed type
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
('apple', 'banana', 'cherry') (1, 5, 7, 9, 3) (True, False, False) (True, 2, 3, 'Hello', 2.5, 0, 1)
In [24]:
# Access item using negative index
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
cherry
In [25]:
# Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5]) # exclude item of 5th index
('cherry', 'orange', 'kiwi')
In [28]:
# Other Examples
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4]) # Start from begining
print("\n")
print(thistuple[2:]) # Till the end
('apple', 'banana', 'cherry', 'orange') ('cherry', 'orange', 'kiwi', 'melon', 'mango')
In [29]:
# Range of Negative Index
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1]) # start from "orange"
('orange', 'kiwi', 'melon')
In [32]:
# Check if an item exist in tuple or not
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
if "orange" not in thistuple:
print("Yes, 'orange' is not present in the fruits tuple")
Yes, 'apple' is in the fruits tuple Yes, 'orange' is not present in the fruits tuple
In [33]:
# Updating tuple
# After creation a tuple its value can't be changed ( As it is immutable )
# We can't add , remove , modify items directly
# Indirect way of changing tuple value
# Convert into list , update it , and again convert into to tuple
# For Ex - Modifying an item
x = ("apple", "banana", "cherry") # Create a tuple
y = list(x) # Convert into list
y[1] = "kiwi" # Modify list item using its index
x = tuple(y) # Convert list into tuple
print(x)
('apple', 'kiwi', 'cherry')
In [34]:
# For Ex - Adding a item in tuple indirectly
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
('apple', 'banana', 'cherry', 'orange')
In [35]:
# Try to add an item direclty into tuple
# Will Raise an Error
thistuple = ("apple", "banana", "cherry")
thistuple.append("orange") # This will raise an error
print(thistuple)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[35], line 5 1 # Try to add an item direclty into tuple 2 # Will Raise an Error 4 thistuple = ("apple", "banana", "cherry") ----> 5 thistuple.append("orange") # This will raise an error 6 print(thistuple) AttributeError: 'tuple' object has no attribute 'append'
In [36]:
# Removing an item from a tuple indirectly
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
('banana', 'cherry')
In [ ]:
In [37]:
# Delete the tuple - using del keyword
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) # this statment will raise an error because the tuple no longer exists
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[37], line 5 3 thistuple = ("apple", "banana", "cherry") 4 del thistuple ----> 5 print(thistuple) NameError: name 'thistuple' is not defined
In [40]:
# Unpacking a tuple
"""
The number of variables must match the number of values in the tuple,
if not, you must use an asterix to collect the remaining values as a list.
"""
fruits = ("apple", "banana", "cherry")
green, yellow, red = fruits # Unpacking of tuple
numbers = ( 1,2,3 )
(x,y,z) = numbers # unpacking of tuple
print(green,yellow,red) # Print variable value seprately
print("\n")
print(x,y,z) # print variable values seprately
apple banana cherry 1 2 3
In [44]:
# If the number of variables is less than the number of values
# Then rest of the values are assigned as a list to a variable defined with * Sign
# For Ex -
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits # A list of remaning items will asssign to red named variable
print(green)
print(yellow)
print(red) # Will print a list
print("type of red variable is " + str(type(red)))
apple banana ['cherry', 'strawberry', 'raspberry'] type of red variable is <class 'list'>
In [45]:
# If the asterix is added to another variable name than the last
# Python will assign values to the variable until the number of values left matches the number of variables left
# For Ex -
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits # Note * assigned to a mid variable
print(green)
print(tropic)
print(red)
apple ['mango', 'papaya', 'pineapple'] cherry
In [46]:
# Itrating tuple items
# For Ex - using for loop
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
apple banana cherry
In [48]:
# For Ex - using index of tuple items
thistuple = ("apple", "banana", "cherry")
for i in range(0,len(thistuple)):
print(thistuple[i])
apple banana cherry
In [50]:
# For Ex - using while loop
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i=i+1
apple banana cherry
In [54]:
# Joining two or more tuples using + operator
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
('a', 'b', 'c', 1, 2, 3)
In [56]:
# Multiplying tuple items - n number of times ( using * operator )
fruits = ("apple", "banana", "cherry")
mytuple1 = fruits * 2
mytuple2 = fruits * 3
print(mytuple1) # Twice the items
print(mytuple2) # Thrice the items
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry') ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
In [60]:
# Built in method of tuple data type
# count() : is used to count number of specific item
# index() : is used to get the index of first appearance of specific item
# For Ex -
fruits = ("apple", "banana", "cherry")
number = (1 ,2, 3, 1, 4, 3, 2 , 3, 5, 6 )
print( "index of 'banana' in fruits is " + str(fruits.index("banana")))
print( "count of '3' in number is " + str(number.count(3)))
index of 'banana' in fruits is 1 count of '3' in number is 3
In [ ]:
No comments:
Post a Comment