Data Structures - Tuple
Tuple is a collection that holds items (of different types). Tuple is ordered and unchangeable.
- Immutable - the programmer can't edit the tuple after its creation - it is not possible to remove or add items.
- Ordered - the indexes of the items don't change.
A tuple can be created by placing the items inside parentheses (item1, item2). The items are separated by a comma.
Here is an example:
#Creating a tuple my_tuple = (1, 2, "python", 3, "tutorial", True) print(my_tuple)
Some operators can work operate with Tuples!
Python concatenates Tuples using the + operator.
It is possible to multiply Tuples using the * operator.
#Operators and Tuples a_tuple = ("python", "tutorial") b_tuple = (5, 10, 20) print(a_tuple + b_tuple) print(a_tuple * 5)
Note that it is not possible to use different types of data structures when concatenating:
#Tuples and Lists a_tuple = ("python", "tutorial") a_list = [5, 10, 20] print(a_tuple + a_list)
We can access to different items of the tuple by putting the appropriate index in square brackets next to the tuple tuple[index]. The index of the first item is 0. It is possible to use the negative index. The negative index of the last items is -1.
Slicing - access to a specified range of elements.. Slicing is made by adding square brackets next to the tuple with the appropriate start index and the end index separated by colon.
- tuple[start : stop]
- tuple[start : stop : step]
#Slicing my_tuple = (1, 2, "python", 3, "tutorial", True) print("The first item of the tuple is", my_tuple) print("The last item of the tuple is", my_tuple[-1]) #range print(my_tuple[2:4])
Tuple - Functions and Methods
Note that Tuples don't have methods like append and remove. That's because tuples are immutable!
The len() function returns the length of a tuple.
#len() our_tuple = ("blue", "green", "gray", "orange") print(len(our_tuple)) print(len(our_tuple) * 2)
The count() method retuns the number of occurrences of a value.
#count our_tuple = (1, 1, 1, 1, 2, 2, 3) print(our_tuple.count(1)) print(our_tuple.count(3))
The index() method retuns the first index of a value.
#index our_tuple = (1, 1, 1, 1, 2, 2, 3) print(our_tuple.index(2)) #slice using the index method print(our_tuple[our_tuple.index(2)])
Try to create a tuple and then slice it
#Slicing #Create your tuple here: #Slice it as you wish :)
- Create a tuple with some items of different types.
- Count the number of occurrences of a certain value.
- Find the first index of that value.
- Print the tuple.
#Create a tuple #Count #Index #Print