0% found this document useful (0 votes)
77 views7 pages

Tuples: 'Physics' 'Chemistry' "A" "B" "C" "D" "E"

Tuples are immutable ordered sequences of values that are indexed and comparable. They are created using parentheses or the tuple() constructor. Tuples can contain heterogeneous data types and are often used as keys in dictionaries since they are hashable unlike lists. Elements in tuples can be accessed using indexes and slices. Tuples support operations like membership, length, max, min but not item assignment since they are immutable. Tuples are commonly used along with other features like tuple unpacking, sorting, dictionary items, and as composite keys in dictionaries.

Uploaded by

sanju kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views7 pages

Tuples: 'Physics' 'Chemistry' "A" "B" "C" "D" "E"

Tuples are immutable ordered sequences of values that are indexed and comparable. They are created using parentheses or the tuple() constructor. Tuples can contain heterogeneous data types and are often used as keys in dictionaries since they are hashable unlike lists. Elements in tuples can be accessed using indexes and slices. Tuples support operations like membership, length, max, min but not item assignment since they are immutable. Tuples are commonly used along with other features like tuple unpacking, sorting, dictionary items, and as composite keys in dictionaries.

Uploaded by

sanju kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

4/4/2020 Chapter10_tuples

TUPLES

Introduction

A tuple is a sequence of immutable Python objects. The values stored in a tuple can be any type and they
are indexed by integers. Tuples are comparabe and hashable so we can sort lists of them and use tuples as
key values in python dictionaries.

• Tuples are sequences, just like lists.

• The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.

• Creating a tuple is as simple as putting different comma-separated values.

• Optionally, you can put these comma-separated values between parentheses also.

Creation of tuples- Example


In [2]:

#creation of tuples
tup1=('physics','chemistry',1997,2000)
tup2=(1,2,3,4,5)
tup3="a","b","c","d","e"
print(tup1)
print(tup2)
print(tup3)

('physics', 'chemistry', 1997, 2000)


(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd', 'e')

In [7]:

#to create a tuple with a single element, comma should be included in the end
t1=('x')
print(type(t1)) #string

t2=('y',)
print(type(t2)) #tuple

<class 'str'>
<class 'tuple'>

Creation of tuples using in-built function - tuple()

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 1/7
4/4/2020 Chapter10_tuples

In [8]:

t=tuple()
print(t)

()

In [9]:

#if the argument is a sequence (string, list or tuple), the result of call to tuple is
a tuple with elements of the sequence:
#tuple is the name of constructor

t=tuple('apple')
print(t)

('a', 'p', 'p', 'l', 'e')

In [13]:

#the bracket operator indexes an element

tup2=(1,2,3,4,5)
print(tup2[0])
print(tup2[1])
print(tup2[10]) #10 is not in range

1
2

--------------------------------------------------------------------------
-
IndexError Traceback (most recent call las
t)
<ipython-input-13-2318b0c9a894> in <module>
4 print(tup2[0])
5 print(tup2[1])
----> 6 print(tup2[10])

IndexError: tuple index out of range

In [14]:

#slice operator selects a range of elements


tup2=(1,2,3,4,5)
print(tup2[1:3])

(2, 3)

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 2/7
4/4/2020 Chapter10_tuples

In [15]:

#trying to modify elements in tuple


t=(1,2,3,4,5)
t[0]='A'

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-15-2a2d2654785a> in <module>
1 #trying to modify elements in tuple
2 t=(1,2,3,4,5)
----> 3 t[0]='A'

TypeError: 'tuple' object does not support item assignment

In [17]:

#Tuple cant be modified, but one tuple can be replaced by other


t=(1,2,3,4,5)
t=('A',)+t[2:] # tuple 2 is replaced by the tuple 'A'
print(t)

('A', 3, 4, 5)

Comparing tuples

• The comparison operators work with tuples and other sequences.

• Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next
element, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they
are really big).

Example

In [18]:

(0,1,2)<(0,3,4)

Out[18]:

True

In [19]:

(0,1,2)>(0,3,4)

Out[19]:

False

DSU Pattern

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 3/7
4/4/2020 Chapter10_tuples

It sorts primarily by first element, but in the case of a tie, it sorts by second element, and so on.

This feature lends itself to a pattern called DSU for

Decorate a sequence by building a list of tuples with one or more sort keys preceding the elements from the
sequence, Sort the list of tuples using the Python built-in sort, and Undecorate by extracting the sorted
elements of the sequence.

In [23]:

#For example, suppose you have a list of words and you want to sort them from longest t
o shortest:

txt = 'hi hello good good moring'


words = txt.split()
t = list()
for word in words:
t.append((len(word), word)) #finding length of the word and

t.sort(reverse=True) #sorting in descending order.

res = list()
for length, word in t:
res.append(word)

print(res)

['moring', 'hello', 'good', 'good', 'hi']

Tuple Assignment
One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an
assignment statement. This allows you to assign more than one variable at a time when the left side is a
sequence.

In [24]:

#In this example we have a two-element list (which is a sequence) and


#assign the first and second elements of the sequence to the variables x and y in a sing
le statement.
m = [ 'have', 'fun' ]
x,y = m
print(x)
print(y)

have
fun

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 4/7
4/4/2020 Chapter10_tuples

In [25]:

#Python roughly translates the tuple assignment syntax to be the following


m = [ 'have', 'fun' ]
x = m[0]
y = m[1]
print(x)
print(y)

have
fun

In [26]:

m = [ 'have', 'fun' ]
(x, y) = m
print(x)
print(y)

have
fun

In [30]:

# tuple assignment allows us to swap the values of two variables in a single statement:
a,b=1,2
a,b = b,a
print(a)
print(b)

2
1

In [33]:

#split of email address and assigning it to tuples


addr='mymail@gmai.com'
uname, domain = addr.split('@')
print(uname)
print(domain)

mymail
gmai.com

# Dictionaries and tuples


Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair

Example

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 5/7
4/4/2020 Chapter10_tuples

In [38]:

d = {'a':10, 'd':1, 'c':22}


t = list(d.items())
print(t)
t.sort()
print(t) #The new list is sorted in ascending alphabetical order by the key value

[('a', 10), ('d', 1), ('c', 22)]


[('a', 10), ('c', 22), ('d', 1)]

Multiple assignment with dictionaries


Combining items, tuple assignment, and for, you can see a nice code pattern for traversing the keys and
values of a dictionary in a single loop

In [40]:

d = {'a':10, 'd':1, 'c':22}


for key, val in list(d.items()): #items returns a list of tuples and key
print(key,val)

a 10
d 1
c 22

In [41]:

#to print in the sorted order


d = {'a':10, 'b':1, 'c':22}
l = list()
for key, val in d.items():
l.append( (val, key) )
print(l)
l.sort(reverse=True)
print(l)

[(10, 'a'), (1, 'b'), (22, 'c')]


[(22, 'c'), (10, 'a'), (1, 'b')]

#The most common words

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 6/7
4/4/2020 Chapter10_tuples

In [42]:

import string
fhand = open('test.txt')
counts = dict()
for line in fhand:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1

# Sort the dictionary by value


lst = list()
for key, val in list(counts.items()):
lst.append((val, key))

lst.sort(reverse=True)

for key, val in lst[:10]:


print(key, val)

3 the
2 than
2 more
2 has
1 with
1 united
1 states
1 spot
1 pandemic
1 new

# Using tuples as keys in dictionary


Because tuples are hashable and lists are not, if we want to create a composite key to use in a dictionary we
must use a tuple as the key.

Example :

Assuming that we have defined the variables last, first, and number, we could write a dictionary assignment
statement as follows:

directory[last,first] = number

The expression in brackets is a tuple. We could use tuple assignment in a for loop to traverse this dictionary.

for last, first in directory: print(first, last, directory[last,first])

This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple to last and
first, then prints the name and corresponding telephone number.

localhost:8888/nbconvert/html/Chapter10_tuples.ipynb?download=false 7/7

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy