avatarRenu Khandelwal

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5253

Abstract

s-symbol">'nuts</span>', <span class="hljs-symbol">'bolts</span>', <span class="hljs-symbol">'hammer</span>', <span class="hljs-symbol">'nail</span> gun')</pre></div><p id="3371">we can also explicitly create two Tuples and concatenate them</p><div id="c9c5"><pre>fortune_500 =('Apple','Google', 'Wal-mart', 'Amazon', 'Microsoft') awesome_companies =('My Company',) awesome_companies += fortune_500 awesome_companies</pre></div><div id="0741"><pre>(<span class="hljs-symbol">'My</span> Company', <span class="hljs-symbol">'Apple</span>', <span class="hljs-symbol">'Google</span>', <span class="hljs-symbol">'Wal-mart</span>', <span class="hljs-symbol">'Amazon</span>', <span class="hljs-symbol">'Microsoft</span>')</pre></div><h1 id="bed1">Accessing values in a Tuple</h1><p id="d959">we can access an individual value or a range of values from a Tuple using the []. This is also referred as slicing</p><p id="8fb8">we can access a single value by providing the index of the element in the Tuple (remember index starts at 0 in python)</p><div id="d6a3"><pre><span class="hljs-built_in">print</span>(awesome_companies[1]</pre></div><div id="5ffd"><pre><span class="hljs-attribute">Apple</span></pre></div><p id="a7bd">We can also access a range of values like from index 2 to 4. Last index 5 will be left off</p><div id="e779"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(awesome_companies[<span class="hljs-number">2</span>:<span class="hljs-number">5</span>])</span></span></pre></div><div id="94eb"><pre>(<span class="hljs-symbol">'Google</span>', <span class="hljs-symbol">'Wal-mart</span>', <span class="hljs-symbol">'Amazon</span>')</pre></div><p id="0780">we can also access all elements from start till a specified range.</p><p id="3f4b">In the below example, we are printing all values from index 1 till end</p><div id="2f72"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(awesome_companies[<span class="hljs-number">1</span>:])</span></span></pre></div><div id="8b34"><pre>(<span class="hljs-symbol">'Apple</span>', <span class="hljs-symbol">'Google</span>', <span class="hljs-symbol">'Wal-mart</span>', <span class="hljs-symbol">'Amazon</span>', <span class="hljs-symbol">'Microsoft</span>')</pre></div><p id="b936">In the below example, we are printing all values from start till 2nd element</p><div id="215a"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(awesome_companies[:<span class="hljs-number">3</span>])</span></span></pre></div><div id="01a0"><pre>(<span class="hljs-symbol">'My</span> Company', <span class="hljs-symbol">'Apple</span>', <span class="hljs-symbol">'Google</span>')</pre></div><h1 id="ae0b">Deleting a Tuple</h1><p id="43aa">Tuples are immutable, so we cannot delete an Individual Item but we can delete the entire Tuple using <b>del</b></p><div id="5743"><pre><span class="hljs-selector-tag">del</span> tool_List</pre></div><h1 id="1dd5">Iterating through a Tuple</h1><p id="b1b7">To iterate through all the elements in a Tuple, we can use a simple for loop as shown below</p><div id="02ce"><pre>for <span class="hljs-selector-tag">i</span> in awesome_companies: <span class="hljs-built_in">print</span>(i)</pre></div><div id="f9a7"><pre><span class="hljs-symbol">My</span> Company <span class="hljs-symbol">Apple</span> <span class="hljs-symbol">Google</span> <span class="hljs-symbol">Wal</span>-<span class="hljs-keyword">mart</span> <span class="hljs-symbol">Amazon</span> <span class="hljs-symbol">Microsoft</span></pre></div><p id="8529">we 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</p><div id="af19"><pre>name = <span class="hljs-built_in">tuple</span>( <span class="hljs-selector-tag">i</span> <span class="hljs-keyword">for</span> <span class="hljs-selector-tag">i</span> <span class="hljs-keyword">in</span> awesome_companies <span class="hljs-keyword">if</span> <span class="hljs-selector-tag">i</span> != <span class="hljs-string">"Apple"</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(name)</span></span></pre></div><div id="d252"><pre>(<span class="hljs-symbol">'My</span> Company', <span class="hljs-symbol">'Google</span>', <span class="hljs-symbol">'Wal-mart</span>', <span class="hljs-symbol">'Amazon</span>', <span class="hljs-symbol">'Microsoft</span>')</pre></div><h1 id="0e1e">Packing and Unpacking of Tuples</h1><p id="6f37">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</p><div id="406c"><pre><span class="hljs-attribute">country</span> = <span class="hljs-string">'USA'</span>, <span class="hljs-string">'Washington D.C.'</span>, <span class="hljs-string">'50'</span>, <span class="hljs-string">'Bald Eagle'</span>, <span class="hljs-string">'Rose'</span> country</pre></div><div id="ce43"><pre>(<span class="hljs-symbol">'USA</span>', <span class="hljs-sym

Options

bol">'Washington</span> D.C.', <span class="hljs-symbol">'50</span>', <span class="hljs-symbol">'Bald</span> Eagle', <span class="hljs-symbol">'Rose</span>')</pre></div><p id="9bcc">Now let’s unpack the Tuple into different variables</p><div id="4cf4"><pre>country_name, capital, no_of_states, national_bird, national_flower, national_animal = country <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(country_name)</span></span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(national_flower)</span></span></pre></div><div id="91cc"><pre><span class="hljs-attribute">USA Rose</span></pre></div><p id="c038">What is the use of packing and Unpacking feature in Tuple?</p><p id="1699">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.</p><p id="bc06">No. of variables while unpacking should be same as the length of the tuple.</p><h1 id="19cb">Tuple to create a dictionary</h1><p id="e7c3">we can use tuple as key/value pair to create a dictionary.</p><p id="b96e">In the example below, we have a tuple t1 and we are creating a dictionary senator with three tuples</p><div id="5427"><pre>t1 =('Constituency','Arizona') senator=dict([('Name', 'John'), ('Age', <span class="hljs-number">85</span>), t1]) senator</pre></div><div id="7aa9"><pre>{'Age': <span class="hljs-number">85</span>, 'Constituency': 'Arizona', 'Name': 'John'}</pre></div><p id="8be0">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.</p><div id="ddb0"><pre>president={(<span class="hljs-number">45</span>, <span class="hljs-string">'Donald'</span>): <span class="hljs-string">'Donald J Trump'</span>} president_44 =(<span class="hljs-number">44</span>,<span class="hljs-string">'Obama'</span>) president[president_44] = <span class="hljs-string">'Barack Hussein Obama'</span> president[(<span class="hljs-number">44</span>,<span class="hljs-string">'Obama'</span>)]</pre></div><h1 id="95e8">Common functions on Tuple</h1><p id="2f1a"><b>len</b>() : returns the length of the tuple</p><div id="655a"><pre><span class="hljs-function"><span class="hljs-title">len</span><span class="hljs-params">(president_44)</span></span></pre></div><div id="63fb"><pre>2</pre></div><p id="d60a"><b>max</b>() : returns the highest value from a tuple</p><p id="176c"><b>min</b>() : returns the lowest value from a tuple</p><p id="52d9"><b>sum</b>() : returns the sum of the values in a tuple</p><p id="ef35"><b>sorted</b>() : returns a sorted version of the tuple</p><div id="a89c"><pre>numbers =(<span class="hljs-number">10</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">100</span>,<span class="hljs-number">500</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(max(numbers)</span></span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(min(numbers)</span></span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(sum(numbers)</span></span>)</pre></div><div id="7f7d"><pre><span class="hljs-number">500</span> <span class="hljs-number">2</span> <span class="hljs-number">616</span> <span class="hljs-string">[2, 4, 10, 100, 500]</span></pre></div><p id="831a">any() — if any of the value in the tuple has a boolean value of True</p><p id="d3df">all() — If all the values in the tuple have a boolean value of True</p><div id="2b28"><pre>test=(<span class="hljs-number">1</span>,<span class="hljs-string">'name'</span>, <span class="hljs-string">'trail'</span>, <span class="hljs-literal">False</span>, <span class="hljs-literal">True</span>) <span class="hljs-built_in">print</span>(<span class="hljs-built_in">any</span>(test)) <span class="hljs-built_in">print</span>(<span class="hljs-built_in">all</span>(test))</pre></div><div id="7992"><pre><span class="hljs-literal">True</span> <span class="hljs-literal">False</span></pre></div><h1 id="eebb">Common methods on tuple</h1><p id="4632">index() : returns the index of the first appearance of the value passed as an argument</p><p id="5466">count() : returns the number of times a value appears in a tuple</p><div id="6a30"><pre>flowers =(<span class="hljs-string">'Rose'</span>, <span class="hljs-string">'Lily'</span>, <span class="hljs-string">'Orchids'</span>, <span class="hljs-string">'Lotus'</span>, <span class="hljs-string">' Mari Gold'</span>, <span class="hljs-string">'Sunflower'</span>,<span class="hljs-string">'Rose'</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(flowers.count(<span class="hljs-string">'Rose'</span>)</span></span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(flowers.index(<span class="hljs-string">'Lotus'</span>)</span></span>)</pre></div><div id="b12f"><pre><span class="hljs-symbol">2 </span> <span class="hljs-number">3</span></pre></div></article></body>

Photo by Dlanor S on Unsplash

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]
Apple

We 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_List

Iterating 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
Microsoft

we 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
Rose

What 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
False

Common 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
Programming
Python
Tuple
List
Dictionary
Recommended from ReadMedium