Tuples in python are similar as Lists.
But tuples are immutable where as lists are mutable. That means you can not change the values of tuple once assigned
Tuples can contain any type of data like lists
Tuples can be created by using parentheses () with comma separated objects and using tuple() built-in function.
We can pass an iterable to tuple() function to create a tuple object.
mytuple = () # Empty tuple
mytuple = tuple() # Empty tuple
print(type(mytuple)) # prints <class 'tuple'>
mytuple = (10, ) # Single value or item to tuples
print(mytuple) # prints (10,)
mytuple = (1, 2, 3, 4, "hello", [7, 8]) # Any data type
print(mytuple) # prints (1, 2, 3, 4, "hello", [7, 8])
list1 = [1, 2, 3, 4, 5] # prints (1, 2, 3, 4, 5)
print(tuple(list1)) # List converted to tuple
<class 'tuple'>
(10,)
(1, 2, 3, 4, "hello", [7, 8])
(1, 2, 3, 4, 5)
To create a single valued tuple you need to use a comma after the item.object like this (10, )
Because without comma like (10)
, it will be considered as the data type of individual object not tuple
t = (10)
print(t)
print(type(t))
30
<class 'int'>
Like lists, the values of a tuple can be accessed busing indexes
mytuple = ("pythoneasy", 2016, "english", ".com", 1, 2, 3, 4)
print(mytuple[1]) # prints 2016 at index 1
print(mytuple[2]) # prints english at index 2
print(mytuple[5]) # prints 2 at index 5
2016
english
2
Accessing elements using negative index also possible in tuples.
Negative indexes starts from -1 to -N from right to left
mytuple = ("pythoneasy", 2016, "english", ".com", 1, 2, 3, 4)
print(mytuple[-6]) # prints "english"
print(mytuple[-1]) # prints 4, the last element
english
mytuple[-1]
always provides the last value.
Like Lists we can also access a range of objects/items from the tuple using slicing
mytuple = ("pythoneasy", 2016, "english", ".com", 1, 2, 3, 4)
print(mytuple[1:4]) # prints (2016, 'english', '.com')
print(mytuple[slice(1, 4)]) # prints (2016, 'english', '.com')
(2016, 'english', '.com')
(2016, 'english', '.com')