SlideShare a Scribd company logo
Tuples
Chapter 10
Python programming Sequence Datatypes -Tuples
Tuples are like lists
• Tuples are another kind of sequence that function much
like a list - they have elements which are indexed
starting at 0
>>> x = ('Glenn', 'Sally', 'Joseph')
>>> print x[2]Joseph
>>> y = ( 1, 9, 2 )
>>> print y
(1, 9, 2)
>>> print max(y)
9
>>> for iter in y:
... print iter
...
1
9
2
>>>
..but.. Tuples are "immutable"
• Unlike a list, once you create a tuple, you cannot alter
its contents - similar to a string
>>> x = [9, 8, 7]
>>> x[2] = 6
>>> print x[9, 8, 6]
>>>
>>> y = 'ABC’
>>> y[2] = 'D’
Traceback:'str'
object does
not support item
Assignment
>>>
>>> z = (5, 4,
3)>>> z[2] = 0
Traceback:'tuple'
object does
not support item
Assignment
>>>
Things not to do with tuples
>>> x = (3, 2, 1)
>>> x.sort()
Traceback:AttributeError: 'tuple' object has no
attribute 'sort’
>>> x.append(5)
Traceback:AttributeError: 'tuple' object has no
attribute 'append’
>>> x.reverse()
Traceback:AttributeError: 'tuple' object has no
attribute 'reverse’
>>>
A Tale of Two Sequences
>>> l = list()
>>> dir(l)[
'append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are more efficient
• Since Python does not have to build tuple structures to
be modifiable, they are simpler and more efficient in
terms of memory use and performance than lists
• So in our program when we are making "temporary
variables" we prefer tuples over lists.
Tuples and Assignment
• We can also put a tuple on the left hand side of an
assignment statement
• We can even omit the parenthesis
>>> (x, y) = (4, 'fred')
>>> print y
Fred
>>> (a, b) = (99, 98)
>>> print a
99
Tuples and
Dictionaries
• The items() method
in dictionaries returns
a list of (key, value)
tuples
>>> d = dict()
>>> d['csev'] = 2
>>> d['cwen'] = 4
>>> for (k,v) in d.items():
... print k, v
...
csev 2
cwen 4
>>> tups = d.items()
>>> print tups
[('csev', 2), ('cwen', 4)]
Tuples are Comparable
• The comparison operators work with tuples and other
sequences If the first item is equal, Python goes on to
the next element, and so on, until it finds elements that
differ.
>>> (0, 1, 2) < (5, 1, 2)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam')
True
>>> ( 'Jones', 'Sally') > ('Adams', 'Sam')
True
Sorting Lists of Tuples
• We can take advantage of the ability to sort a list of
tuples to get a sorted version of a dictionary
• First we sort the dictionary by the key using the items()
method
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = d.items()
>>> t
[('a', 10), ('c', 22), ('b', 1)]
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]
Using
sorted()
>>> d = {'a':10, 'b':1, 'c':22}
>>> d.items()
[('a', 10), ('c', 22), ('b', 1)]
>>> t = sorted(d.items())
>>> t
[('a', 10), ('b', 1), ('c', 22)]
>>> for k, v in sorted(d.items()):
... print k, v
...
a 10
b 1
c 22
We can do this even
more directly using the
built-in function sorted
that takes a sequence
as a parameter and
returns a sorted
sequence
Sort by values instead of key
• If we could
construct a list of
tuples of the form
(value, key) we
could sort by
value
• We do this with a
for loop that
creates a list of
tuples
>>> c = {'a':10, 'b':1, 'c':22}
>>> tmp = list()
>>> for k, v in c.items() :
... tmp.append( (v, k) )
...
>>> print tmp
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> tmp.sort(reverse=True)
>>> print tmp
[(22, 'c'), (10, 'a'), (1, 'b')]
fhand = open('romeo.txt')
counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0 ) + 1
lst = list()
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse=True)
for val, key in lst[:10] :
print key, val
The top 10 most
common words.
Even Shorter Version (adv)
http://wiki.python.org/moin/HowTo/Sorti
ng
>>> c = {'a':10, 'b':1, 'c':22}
>>> print sorted( [ (v,k) for k,v in c.items() ] )
[(1, 'b'), (10, 'a'), (22, 'c')]
List comprehension creates a dynamic list. In this case, we
make a list of reversed tuples and then sort it.
Summary
• Tuple syntax
• Mutability (not)
• Comparability
• Sortable
• Tuples in assignment
statements
• Using sorted()
• Sorting dictionaries by either
key or value
Ad

Recommended

Pytho_tuples
Pytho_tuples
BMS Institute of Technology and Management
 
Python data structures
Python data structures
Harry Potter
 
Python data structures
Python data structures
Tony Nguyen
 
Python data structures
Python data structures
Young Alista
 
Python data structures
Python data structures
James Wong
 
Python data structures
Python data structures
Luis Goldster
 
Python data structures
Python data structures
Fraboni Ec
 
Python Lecture 11
Python Lecture 11
Inzamam Baig
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
 
Lecture 09.pptx
Lecture 09.pptx
Mohammad Hassan
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
tupple.pptx
tupple.pptx
satyabratPanda2
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdf
Koteswari Kasireddy
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
pythonlist_arrays_and some practice problems
pythonlist_arrays_and some practice problems
Abhi Marvel
 
Programming in Python Lists and its methods .ppt
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
 
Python tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
datastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
Understanding-Python-Data-Structures-A-Comprehensive-Guide.pptx
Understanding-Python-Data-Structures-A-Comprehensive-Guide.pptx
riberim258
 
Sixth session
Sixth session
AliMohammad155
 
Python programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python list tuple dictionary .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
Tuples.pptx
Tuples.pptx
AnuragBharti27
 
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
resming1
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 

More Related Content

Similar to Python programming Sequence Datatypes -Tuples (20)

Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
 
Lecture 09.pptx
Lecture 09.pptx
Mohammad Hassan
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
tupple.pptx
tupple.pptx
satyabratPanda2
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdf
Koteswari Kasireddy
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
pythonlist_arrays_and some practice problems
pythonlist_arrays_and some practice problems
Abhi Marvel
 
Programming in Python Lists and its methods .ppt
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
 
Python tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
datastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
Understanding-Python-Data-Structures-A-Comprehensive-Guide.pptx
Understanding-Python-Data-Structures-A-Comprehensive-Guide.pptx
riberim258
 
Sixth session
Sixth session
AliMohammad155
 
Python programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python list tuple dictionary .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
Tuples.pptx
Tuples.pptx
AnuragBharti27
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
pythonlist_arrays_and some practice problems
pythonlist_arrays_and some practice problems
Abhi Marvel
 
Python tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
datastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
Understanding-Python-Data-Structures-A-Comprehensive-Guide.pptx
Understanding-Python-Data-Structures-A-Comprehensive-Guide.pptx
riberim258
 
Python list tuple dictionary .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 

Recently uploaded (20)

Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
resming1
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
AI_Presentation (1). Artificial intelligence
AI_Presentation (1). Artificial intelligence
RoselynKaur8thD34
 
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Mark Billinghurst
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
System design handwritten notes guidance
System design handwritten notes guidance
Shabista Imam
 
دراسة حاله لقرية تقع في جنوب غرب السودان
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
retina_biometrics ruet rajshahi bangdesh.pptx
retina_biometrics ruet rajshahi bangdesh.pptx
MdRakibulIslam697135
 
Mobile database systems 20254545645.pptx
Mobile database systems 20254545645.pptx
herosh1968
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
Structural Wonderers_new and ancient.pptx
Structural Wonderers_new and ancient.pptx
nikopapa113
 
Industrial internet of things IOT Week-3.pptx
Industrial internet of things IOT Week-3.pptx
KNaveenKumarECE
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
輪読会資料_Miipher and Miipher2 .
輪読会資料_Miipher and Miipher2 .
NABLAS株式会社
 
International Journal of Advanced Information Technology (IJAIT)
International Journal of Advanced Information Technology (IJAIT)
ijait
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
Proposal for folders structure division in projects.pdf
Proposal for folders structure division in projects.pdf
Mohamed Ahmed
 
NEW Strengthened Senior High School Gen Math.pptx
NEW Strengthened Senior High School Gen Math.pptx
DaryllWhere
 
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
resming1
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
AI_Presentation (1). Artificial intelligence
AI_Presentation (1). Artificial intelligence
RoselynKaur8thD34
 
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Mark Billinghurst
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
System design handwritten notes guidance
System design handwritten notes guidance
Shabista Imam
 
دراسة حاله لقرية تقع في جنوب غرب السودان
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
retina_biometrics ruet rajshahi bangdesh.pptx
retina_biometrics ruet rajshahi bangdesh.pptx
MdRakibulIslam697135
 
Mobile database systems 20254545645.pptx
Mobile database systems 20254545645.pptx
herosh1968
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
Structural Wonderers_new and ancient.pptx
Structural Wonderers_new and ancient.pptx
nikopapa113
 
Industrial internet of things IOT Week-3.pptx
Industrial internet of things IOT Week-3.pptx
KNaveenKumarECE
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
輪読会資料_Miipher and Miipher2 .
輪読会資料_Miipher and Miipher2 .
NABLAS株式会社
 
International Journal of Advanced Information Technology (IJAIT)
International Journal of Advanced Information Technology (IJAIT)
ijait
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
Proposal for folders structure division in projects.pdf
Proposal for folders structure division in projects.pdf
Mohamed Ahmed
 
NEW Strengthened Senior High School Gen Math.pptx
NEW Strengthened Senior High School Gen Math.pptx
DaryllWhere
 
Ad

Python programming Sequence Datatypes -Tuples

  • 3. Tuples are like lists • Tuples are another kind of sequence that function much like a list - they have elements which are indexed starting at 0 >>> x = ('Glenn', 'Sally', 'Joseph') >>> print x[2]Joseph >>> y = ( 1, 9, 2 ) >>> print y (1, 9, 2) >>> print max(y) 9 >>> for iter in y: ... print iter ... 1 9 2 >>>
  • 4. ..but.. Tuples are "immutable" • Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string >>> x = [9, 8, 7] >>> x[2] = 6 >>> print x[9, 8, 6] >>> >>> y = 'ABC’ >>> y[2] = 'D’ Traceback:'str' object does not support item Assignment >>> >>> z = (5, 4, 3)>>> z[2] = 0 Traceback:'tuple' object does not support item Assignment >>>
  • 5. Things not to do with tuples >>> x = (3, 2, 1) >>> x.sort() Traceback:AttributeError: 'tuple' object has no attribute 'sort’ >>> x.append(5) Traceback:AttributeError: 'tuple' object has no attribute 'append’ >>> x.reverse() Traceback:AttributeError: 'tuple' object has no attribute 'reverse’ >>>
  • 6. A Tale of Two Sequences >>> l = list() >>> dir(l)[ 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> t = tuple() >>> dir(t) ['count', 'index']
  • 7. Tuples are more efficient • Since Python does not have to build tuple structures to be modifiable, they are simpler and more efficient in terms of memory use and performance than lists • So in our program when we are making "temporary variables" we prefer tuples over lists.
  • 8. Tuples and Assignment • We can also put a tuple on the left hand side of an assignment statement • We can even omit the parenthesis >>> (x, y) = (4, 'fred') >>> print y Fred >>> (a, b) = (99, 98) >>> print a 99
  • 9. Tuples and Dictionaries • The items() method in dictionaries returns a list of (key, value) tuples >>> d = dict() >>> d['csev'] = 2 >>> d['cwen'] = 4 >>> for (k,v) in d.items(): ... print k, v ... csev 2 cwen 4 >>> tups = d.items() >>> print tups [('csev', 2), ('cwen', 4)]
  • 10. Tuples are Comparable • The comparison operators work with tuples and other sequences If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ. >>> (0, 1, 2) < (5, 1, 2) True >>> (0, 1, 2000000) < (0, 3, 4) True >>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam') True >>> ( 'Jones', 'Sally') > ('Adams', 'Sam') True
  • 11. Sorting Lists of Tuples • We can take advantage of the ability to sort a list of tuples to get a sorted version of a dictionary • First we sort the dictionary by the key using the items() method >>> d = {'a':10, 'b':1, 'c':22} >>> t = d.items() >>> t [('a', 10), ('c', 22), ('b', 1)] >>> t.sort() >>> t [('a', 10), ('b', 1), ('c', 22)]
  • 12. Using sorted() >>> d = {'a':10, 'b':1, 'c':22} >>> d.items() [('a', 10), ('c', 22), ('b', 1)] >>> t = sorted(d.items()) >>> t [('a', 10), ('b', 1), ('c', 22)] >>> for k, v in sorted(d.items()): ... print k, v ... a 10 b 1 c 22 We can do this even more directly using the built-in function sorted that takes a sequence as a parameter and returns a sorted sequence
  • 13. Sort by values instead of key • If we could construct a list of tuples of the form (value, key) we could sort by value • We do this with a for loop that creates a list of tuples >>> c = {'a':10, 'b':1, 'c':22} >>> tmp = list() >>> for k, v in c.items() : ... tmp.append( (v, k) ) ... >>> print tmp [(10, 'a'), (22, 'c'), (1, 'b')] >>> tmp.sort(reverse=True) >>> print tmp [(22, 'c'), (10, 'a'), (1, 'b')]
  • 14. fhand = open('romeo.txt') counts = dict() for line in fhand: words = line.split() for word in words: counts[word] = counts.get(word, 0 ) + 1 lst = list() for key, val in counts.items(): lst.append( (val, key) ) lst.sort(reverse=True) for val, key in lst[:10] : print key, val The top 10 most common words.
  • 15. Even Shorter Version (adv) http://wiki.python.org/moin/HowTo/Sorti ng >>> c = {'a':10, 'b':1, 'c':22} >>> print sorted( [ (v,k) for k,v in c.items() ] ) [(1, 'b'), (10, 'a'), (22, 'c')] List comprehension creates a dynamic list. In this case, we make a list of reversed tuples and then sort it.
  • 16. Summary • Tuple syntax • Mutability (not) • Comparability • Sortable • Tuples in assignment statements • Using sorted() • Sorting dictionaries by either key or value