Python Data Structures — Tuple
Prerequisites : Basic knowledge of any programming language
we will explore Data Structure Tuples and all its operations here.
For all operation on List read this post — https://readmedium.com/python-data-structures-list-9131e7386c8d
For all operation on Dictionary read this post — https://readmedium.com/python-data-structures-dictionary-9b746b94b421
To explore about Tuples refer to -https://github.com/arshren/Data-Structures/blob/master/Python%20Data%20Structures%20-%20Tuple.ipynb
all outputs are in bold and italics
What is a sequence?
A sequence is a generic terms for any ordered sets like Tuples, Sets or Strings
so, let’s start with Tuples
Tuples
Tuples are immutables, that means once defined, individual value of an item cannot be edited or deleted. This makes them faster than List.
we can reassign a tuple or delete an entire Tuple.
Tuples can contain different data types like string, numbers etc.
They can contain duplicate values
Tuples can be accessed via unpacking or indexing.(This will be explained further)
when are Tuples useful?
Tuples should be used when you do not want to manipulate the data
They are faster than list
Can be used as keys in dictionaries
Now we will go step by step into defining a Tuple, Adding elements in a Tuple, accessing elements in a Tuple, deleting a Tuple, and then iterating through the Tuple. we also look at packing and unpacking of a tuple and using Tuple to build dictionary
Defining a Tuple
Tuple can be defined by a comma separated values inside a parenthesis ( )
tool_List =('screwdriver', 'spanner', 'nuts', 'bolts', 'hammer')
tool_List('screwdriver', 'spanner', 'nuts', 'bolts', 'hammer')Tuples allow for duplicate values
tool_List =('screwdriver', 'spanner', 'nuts', 'bolts', 'hammer', 'spanner')
tool_List('screwdriver', 'spanner', 'nuts', 'bolts', 'hammer', 'spanner')we can also create a tuple without using parenthesis
tool_List = 'screwdriver', 'spanner', 'nuts', 'bolts', 'hammer'
tool_List('screwdriver', 'spanner', 'nuts', 'bolts', 'hammer')Concatenating values in a Tuple
only a Tuple can be concatenated to a Tuple. A string cannot be concatenated to a Tuple
Below, I will concatenate a “nail gun” to the tool_List. Since a Tuple only can be concatenated to a Tuple notice the “,” at the end
tool_List += ('nail gun',)
tool_List('screwdriver', 'spanner', 'nuts', 'bolts', 'hammer', 'nail gun')we can also explicitly create two Tuples and concatenate them
fortune_500 =('Apple','Google', 'Wal-mart', 'Amazon', 'Microsoft')
awesome_companies =('My Company',)
awesome_companies += fortune_500
awesome_companies('My Company', 'Apple', 'Google', 'Wal-mart', 'Amazon', 'Microsoft')Accessing values in a Tuple
we can access an individual value or a range of values from a Tuple using the []. This is also referred as slicing
we can access a single value by providing the index of the element in the Tuple (remember index starts at 0 in python)
print(awesome_companies[1]AppleWe can also access a range of values like from index 2 to 4. Last index 5 will be left off
print(awesome_companies[2:5])('Google', 'Wal-mart', 'Amazon')we can also access all elements from start till a specified range.
In the below example, we are printing all values from index 1 till end
print(awesome_companies[1:])('Apple', 'Google', 'Wal-mart', 'Amazon', 'Microsoft')In the below example, we are printing all values from start till 2nd element
print(awesome_companies[:3])('My Company', 'Apple', 'Google')Deleting a Tuple
Tuples are immutable, so we cannot delete an Individual Item but we can delete the entire Tuple using del
del tool_ListIterating through a Tuple
To iterate through all the elements in a Tuple, we can use a simple for loop as shown below
for i in awesome_companies:
print(i)My Company
Apple
Google
Wal-mart
Amazon
Microsoftwe can use Tuple comprehension along with a conditions. Here we are iterating through awesome_companies and checking if the awesome_companies is not “Apple” then adding the element into name tuple
name = tuple( i for i in awesome_companies if i != "Apple")
print(name)('My Company', 'Google', 'Wal-mart', 'Amazon', 'Microsoft')Packing and Unpacking of Tuples
packing allows you to create a Tuple on the fly where we do not use normal notation of creating a Tuple. While packing we place the values in a Tuple and during unpacking we extract those values back into variables
country = 'USA', 'Washington D.C.', '50', 'Bald Eagle', 'Rose'
country('USA', 'Washington D.C.', '50', 'Bald Eagle', 'Rose')Now let’s unpack the Tuple into different variables
country_name, capital, no_of_states, national_bird, national_flower, national_animal = country
print(country_name)
print(national_flower)USA
RoseWhat is the use of packing and Unpacking feature in Tuple?
if you look at the example above, with one statement we were able to create and assign 6 different variables in one single statement from a Tuple and that is the power of packing and unpacking a tuple.
No. of variables while unpacking should be same as the length of the tuple.
Tuple to create a dictionary
we can use tuple as key/value pair to create a dictionary.
In the example below, we have a tuple t1 and we are creating a dictionary senator with three tuples
t1 =('Constituency','Arizona')
senator=dict([('Name', 'John'), ('Age', 85), t1])
senator{'Age': 85, 'Constituency': 'Arizona', 'Name': 'John'}we can also use tuple as keys in a dictionary. In the example below, we have a tuple with values 44 and Obama and we assigned that as the key in the dictionary president.
president={(45, 'Donald'): 'Donald J Trump'}
president_44 =(44,'Obama')
president[president_44] = 'Barack Hussein Obama'
president[(44,'Obama')]Common functions on Tuple
len() : returns the length of the tuple
len(president_44)2
max() : returns the highest value from a tuple
min() : returns the lowest value from a tuple
sum() : returns the sum of the values in a tuple
sorted() : returns a sorted version of the tuple
numbers =(10,2,4,100,500)
print(max(numbers))
print(min(numbers))
print(sum(numbers))500
2
616
[2, 4, 10, 100, 500]any() — if any of the value in the tuple has a boolean value of True
all() — If all the values in the tuple have a boolean value of True
test=(1,'name', 'trail', False, True)
print(any(test))
print(all(test))True
FalseCommon methods on tuple
index() : returns the index of the first appearance of the value passed as an argument
count() : returns the number of times a value appears in a tuple
flowers =('Rose', 'Lily', 'Orchids', 'Lotus', ' Mari Gold', 'Sunflower','Rose')
print(flowers.count('Rose'))
print(flowers.index('Lotus'))2
3