SlideShare a Scribd company logo
Swarup Kr Ghosh
MIS Group
IIM Calcutta
swarupg1@gmail.com
 Tuples
 Lists
 Strings
 Dictionaries
7/21/2017 2Swarup Kr Ghosh
 All three sequence types share much of the same
syntax and functionality
 Tuple
◦ A simple immutable ordered sequence of items
◦ Items can be of mixed types, including collection types
 List
◦ Mutable ordered sequence of items of mixed types
 Strings
◦ Immutable
◦ Conceptually very much like a tuple
7/21/2017 3Swarup Kr Ghosh
 Tuples are defined using parentheses (and commas)
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
 Lists are defined using square brackets (and
commas)
>>> li = [“abc”, 34, 4.34, 23]
 Strings are defined using quotes (“, ‘, or “““)
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
7/21/2017 4Swarup Kr Ghosh
 We can access individual members of a tuple, list, or
string using square bracket “array” notation
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] #Second item in the tuple
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] #Second item in the list
34
>>> st = “Hello World”
>>> st[1] #Second character in string
‘e’
7/21/2017 5Swarup Kr Ghosh
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
 Positive index: count from the left, starting with 0.
>>> t[1]
‘abc’
 Negative lookup: count from right, starting with -1
>>> t[-3]
4.56
7/21/2017 6Swarup Kr Ghosh
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
 Return a copy of the container with a subset of the
original members
 Start copying at the first index, and stop copying
before the second index
>>> t[1:4]
(‘abc’, 4.56, (2,3))
 You can also use negative indices when slicing
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
7/21/2017 7Swarup Kr Ghosh
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
 Omit the first index to make a copy starting from the
beginning of the container
>>> t[:2]
(23, ‘abc’)
 Omit the second index to make a copy starting at
the first index and going to the end of the container
>>> t[2:]
(4.56, (2,3), ‘def’)
7/21/2017 8Swarup Kr Ghosh
 To make a copy of an entire sequence, use ‘[:]’
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
 Note the difference between these two lines for
mutable sequences:
>>> list2 = list1 # 2 names refer to 1 ref
# Changing one affects both
>>> list2 = list1[:] # Two independent copies, two refs
7/21/2017 9Swarup Kr Ghosh
 Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
 For strings, tests for substrings:
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
 Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions
7/21/2017 10Swarup Kr Ghosh
 The + operator produces a new tuple, list, or string
whose value is the concatenation of its arguments
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> “Hello” + “ ” + “World”
‘Hello World’
 The * operator produces a new tuple, list, or string that
repeats the original content
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
7/21/2017 11Swarup Kr Ghosh
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -topleveltu[
2] = 3.14
TypeError: object doesn't support item assignment
 You can’t change a tuple
 You can make a fresh tuple and assign its reference to a
previously used name
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
7/21/2017 12Swarup Kr Ghosh
 The comma is the tuple creation operator, not
parens
>>> 1,
(1,)
 Python shows parens for clarity (best practice)
>>> (1,)
(1,)
 Don't forget the comma!
>>> (1)
1
 Trailing comma only required for singletons others
 Empty tuples have a special syntactic form
>>> ()1313
()
>>> tuple()
()
7/21/2017 13Swarup Kr Ghosh
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
 We can change lists in place
 Name ‘li’ still points to the same memory
reference when we’re done
 The mutability of lists means that they aren’t as
fast as tuples
7/21/2017 14Swarup Kr Ghosh
 append:
>>> li = [1, 11, 3, 4, 5]
>>> li.append(‘a’) # Our first exposure to method syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]
 insert:
>>> li.insert(2, ‘i’)
>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
 extend:
>>> li.extend([9, 8, 7])
>>>li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]
7/21/2017 15Swarup Kr Ghosh
 + creates a fresh list (with a new memory reference)
 extend operates on list ‘li’ in place
>>> li.extend([9, 8, 7])
>>>li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]
 Confusing: extend vs append
◦ Extend takes a list as an argument
◦ Append takes a singleton as an argument
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
7/21/2017 16Swarup Kr Ghosh
a
1 2 3
b
a
1 2 3
b
4
a = [1, 2, 3]
a.append(4)
b = a
a
1 2 3
7/21/2017 17Swarup Kr Ghosh
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
 Index:
>>> li.index(‘b’) # index of first occurrence
1
 Count:
>>> li.count(‘b’) # number of occurrences
2
 Remove:
>>> li.remove(‘b’) # remove first occurrence
>>> li
[‘a’, ‘c’, ‘b’]
7/21/2017 18Swarup Kr Ghosh
>>> li = [5, 2, 6, 8]
 Reverse:
>>> li.reverse() # reverse the list
>>> li
[8, 6, 2, 5]
 Sort:
>>> li.sort() # sort the list
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
7/21/2017 19Swarup Kr Ghosh
 Lists slower but more powerful than tuples
◦ Lists can be modified, and they have lots of handy
operations we can perform on them
◦ Tuples are immutable and have fewer features
 To convert between tuples and lists use the list()
and tuple() functions:
◦ li = list(tu)
◦ tu = tuple(li)
7/21/2017 20Swarup Kr Ghosh
Matrix:
>>> m=[[1,2,3],
[4,5,6],
[7,8,9]]
>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> n=[[1,1,1],
[1,1,1],
[1,1,1]]
>>> n
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> m+n
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
#Concatination not addition
7/21/2017 21Swarup Kr Ghosh
 cross products:
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [x+y for x in vec1 and y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8,12,-54]
7/21/2017 22Swarup Kr Ghosh
 can also use if:
>>> vec1 = [2,4,6]
>>> [3*x for x in vec1 if x > 3]
[12, 18]
>>> [3*x for x in vec1 if x < 2]
[]
7/21/2017 23Swarup Kr Ghosh
 Dictionaries store a mapping between a set of keys
and a set of values
◦ Keys can be any immutable type
◦ Accessed by key, not offset position
◦ Unordered collections of arbitrary objects
◦ Variable-length, heterogeneous, and arbitrarily nestable
◦ Tables of object references (hash tables)
◦ Values can be any type
◦ A single dictionary can store values of different types
 You can define, modify, view, lookup, and delete the
key-value pairs in the dictionary.
7/21/2017 24Swarup Kr Ghosh
 Name={key : value,…… }
 Name[key]----- Shows value of Dictionary
d={'user':'scott','pswd':12345}
>>> d['user']
'scott'
>>> d['pswd']
12345
>>> d['scott']
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
d['scott']
KeyError: 'scott'
7/21/2017 25Swarup Kr Ghosh
 To change values:
>>> d['user']='tiger'
>>> d
{'user': 'tiger', 'pswd': 12345}
 To insert another key with value:
>>> d['id']=45
>>> d
{'user': 'tiger', 'pswd': 12345, 'id': 45}
 Keys() method:
>>> d.keys()
dict_keys(['user', 'pswd', 'id'])
 Item() method:
>>> d.items()
dict_items([('user', 'tiger'), ('pswd', 12345), ('id', 45)])
7/21/2017 26Swarup Kr Ghosh
 Del() method:
>>> del(d['user'])
>>> d
{'pswd': 12345, 'id': 45}
 Clear() method:
>>> d.clear()
>>> d
{}
 To show all keys and values with specific format:
>>> for k in sorted(d.keys()):
print('key:',k,'->',d[k])
key: id -> 45
key: pswd -> 12345
key: user -> tiger
7/21/2017 27Swarup Kr Ghosh
>>> table = {'1975': 'Holy Grail',
'1979': 'Life of Brian', '1983': 'The Meaning of Life'}
>>> year = '1983'
>>> movie = table[year]
>>> movie
'The Meaning of Life‘
>>> for year in table:
print(year + 't' + table[year])
1979 Life of Brian
1975 Holy Grail
1983 The Meaning of Life
7/21/2017Swarup Kr Ghosh 28
7/21/2017Swarup Kr Ghosh 29
7/21/2017 30Swarup Kr Ghosh

More Related Content

PPTX
Python lec5
Swarup Ghosh
 
PPTX
Python lec4
Swarup Ghosh
 
PPTX
Super Advanced Python –act1
Ke Wei Louis
 
PDF
Day 4a iteration and functions.pptx
Adrien Melquiond
 
PDF
Day 4b iteration and functions for-loops.pptx
Adrien Melquiond
 
PDF
How to clean an array
Andrew Shitov
 
PDF
Groovy collection api
trygvea
 
PDF
First step of Performance Tuning
risou
 
Python lec5
Swarup Ghosh
 
Python lec4
Swarup Ghosh
 
Super Advanced Python –act1
Ke Wei Louis
 
Day 4a iteration and functions.pptx
Adrien Melquiond
 
Day 4b iteration and functions for-loops.pptx
Adrien Melquiond
 
How to clean an array
Andrew Shitov
 
Groovy collection api
trygvea
 
First step of Performance Tuning
risou
 

What's hot (19)

PDF
Color picker2
ArnabBandopadhyaya
 
PPTX
Five
Łukasz Langa
 
PDF
python高级内存管理
rfyiamcool
 
PDF
groovy databases
Paul King
 
PPTX
Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alina Vilk
 
PPTX
Cassandra into
DataArt
 
PPTX
2013 0928 programming by cuda
小明 王
 
DOCX
Lispprograaming excercise
ilias ahmed
 
PDF
はじめてのGroovy
Tsuyoshi Yamamoto
 
PPTX
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
it-people
 
PDF
Everything is composable
Victor Igor
 
PDF
Elm: give it a try
Eugene Zharkov
 
PDF
Cycle.js: Functional and Reactive
Eugene Zharkov
 
PDF
Being Google
Tom Dyson
 
PDF
Useful javascript
Lei Kang
 
PDF
Python memory management_v2
Jeffrey Clark
 
PDF
MySQL 8.0 Preview: What Is Coming?
Gabriela Ferrara
 
DOCX
Dmxedit
Eddy_TKJ
 
Color picker2
ArnabBandopadhyaya
 
python高级内存管理
rfyiamcool
 
groovy databases
Paul King
 
Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alina Vilk
 
Cassandra into
DataArt
 
2013 0928 programming by cuda
小明 王
 
Lispprograaming excercise
ilias ahmed
 
はじめてのGroovy
Tsuyoshi Yamamoto
 
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
it-people
 
Everything is composable
Victor Igor
 
Elm: give it a try
Eugene Zharkov
 
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Being Google
Tom Dyson
 
Useful javascript
Lei Kang
 
Python memory management_v2
Jeffrey Clark
 
MySQL 8.0 Preview: What Is Coming?
Gabriela Ferrara
 
Dmxedit
Eddy_TKJ
 
Ad

Similar to Python lec2 (20)

PPTX
Python lec3
Swarup Ghosh
 
PPTX
Sequence Types in Python Programming
Bobby Murugesan
 
PDF
Day 1d R structures & objects: matrices and data frames.pptx
Adrien Melquiond
 
PDF
Numpy tutorial(final) 20160303
Namgee Lee
 
PPTX
python chapter 1
Raghu nath
 
PPTX
Python chapter 2
Raghu nath
 
PPTX
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
SovannDoeur
 
PDF
Python lecture 05
Tanwir Zaman
 
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Guru Nanak Technical Institutions
 
PDF
Basic R Data Manipulation
Chu An
 
PDF
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
PPTX
R programming
Pramodkumar Jha
 
PDF
[1062BPY12001] Data analysis with R / week 2
Kevin Chun-Hsien Hsu
 
PPT
Data types usually used in python for coding
PriyankaRajaboina
 
PPT
02python.ppt
ssuser492e7f
 
PPT
02python.ppt
rehanafarheenece
 
PPTX
Ruby's Arrays and Hashes with examples
Niranjan Sarade
 
PDF
Day 2 repeats.pptx
Adrien Melquiond
 
PPTX
Python list tuple dictionary .pptx
miteshchaudhari4466
 
PPT
Python
Vishal Sancheti
 
Python lec3
Swarup Ghosh
 
Sequence Types in Python Programming
Bobby Murugesan
 
Day 1d R structures & objects: matrices and data frames.pptx
Adrien Melquiond
 
Numpy tutorial(final) 20160303
Namgee Lee
 
python chapter 1
Raghu nath
 
Python chapter 2
Raghu nath
 
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
SovannDoeur
 
Python lecture 05
Tanwir Zaman
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Guru Nanak Technical Institutions
 
Basic R Data Manipulation
Chu An
 
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
R programming
Pramodkumar Jha
 
[1062BPY12001] Data analysis with R / week 2
Kevin Chun-Hsien Hsu
 
Data types usually used in python for coding
PriyankaRajaboina
 
02python.ppt
ssuser492e7f
 
02python.ppt
rehanafarheenece
 
Ruby's Arrays and Hashes with examples
Niranjan Sarade
 
Day 2 repeats.pptx
Adrien Melquiond
 
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Ad

Recently uploaded (20)

PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
TumwineRobert
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
Marta Fijak
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
Cardiovascular Pharmacology for pharmacy students.pptx
TumwineRobert
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
The Final Stretch: How to Release a Game and Not Die in the Process.
Marta Fijak
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Understanding operators in c language.pptx
auteharshil95
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Landforms and landscapes data surprise preview
jpinnuck
 
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 

Python lec2

  • 2.  Tuples  Lists  Strings  Dictionaries 7/21/2017 2Swarup Kr Ghosh
  • 3.  All three sequence types share much of the same syntax and functionality  Tuple ◦ A simple immutable ordered sequence of items ◦ Items can be of mixed types, including collection types  List ◦ Mutable ordered sequence of items of mixed types  Strings ◦ Immutable ◦ Conceptually very much like a tuple 7/21/2017 3Swarup Kr Ghosh
  • 4.  Tuples are defined using parentheses (and commas) >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)  Lists are defined using square brackets (and commas) >>> li = [“abc”, 34, 4.34, 23]  Strings are defined using quotes (“, ‘, or “““) >>> st = “Hello World” >>> st = ‘Hello World’ >>> st = “““This is a multi-line string that uses triple quotes.””” 7/21/2017 4Swarup Kr Ghosh
  • 5.  We can access individual members of a tuple, list, or string using square bracket “array” notation >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) >>> tu[1] #Second item in the tuple ‘abc’ >>> li = [“abc”, 34, 4.34, 23] >>> li[1] #Second item in the list 34 >>> st = “Hello World” >>> st[1] #Second character in string ‘e’ 7/21/2017 5Swarup Kr Ghosh
  • 6. >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)  Positive index: count from the left, starting with 0. >>> t[1] ‘abc’  Negative lookup: count from right, starting with -1 >>> t[-3] 4.56 7/21/2017 6Swarup Kr Ghosh
  • 7. >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)  Return a copy of the container with a subset of the original members  Start copying at the first index, and stop copying before the second index >>> t[1:4] (‘abc’, 4.56, (2,3))  You can also use negative indices when slicing >>> t[1:-1] (‘abc’, 4.56, (2,3)) 7/21/2017 7Swarup Kr Ghosh
  • 8. >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)  Omit the first index to make a copy starting from the beginning of the container >>> t[:2] (23, ‘abc’)  Omit the second index to make a copy starting at the first index and going to the end of the container >>> t[2:] (4.56, (2,3), ‘def’) 7/21/2017 8Swarup Kr Ghosh
  • 9.  To make a copy of an entire sequence, use ‘[:]’ >>> t[:] (23, ‘abc’, 4.56, (2,3), ‘def’)  Note the difference between these two lines for mutable sequences: >>> list2 = list1 # 2 names refer to 1 ref # Changing one affects both >>> list2 = list1[:] # Two independent copies, two refs 7/21/2017 9Swarup Kr Ghosh
  • 10.  Boolean test whether a value is inside a container: >>> t = [1, 2, 4, 5] >>> 3 in t False >>> 4 in t True >>> 4 not in t False  For strings, tests for substrings: >>> a = 'abcde' >>> 'c' in a True >>> 'cd' in a True >>> 'ac' in a False  Be careful: the in keyword is also used in the syntax of for loops and list comprehensions 7/21/2017 10Swarup Kr Ghosh
  • 11.  The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments >>> (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] >>> “Hello” + “ ” + “World” ‘Hello World’  The * operator produces a new tuple, list, or string that repeats the original content >>> (1, 2, 3) * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> “Hello” * 3 ‘HelloHelloHello’ 7/21/2017 11Swarup Kr Ghosh
  • 12. >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) >>> t[2] = 3.14 Traceback (most recent call last): File "<pyshell#75>", line 1, in -topleveltu[ 2] = 3.14 TypeError: object doesn't support item assignment  You can’t change a tuple  You can make a fresh tuple and assign its reference to a previously used name >>> t = (23, ‘abc’, 3.14, (2,3), ‘def’) 7/21/2017 12Swarup Kr Ghosh
  • 13.  The comma is the tuple creation operator, not parens >>> 1, (1,)  Python shows parens for clarity (best practice) >>> (1,) (1,)  Don't forget the comma! >>> (1) 1  Trailing comma only required for singletons others  Empty tuples have a special syntactic form >>> ()1313 () >>> tuple() () 7/21/2017 13Swarup Kr Ghosh
  • 14. >>> li = [‘abc’, 23, 4.34, 23] >>> li[1] = 45 >>> li [‘abc’, 45, 4.34, 23]  We can change lists in place  Name ‘li’ still points to the same memory reference when we’re done  The mutability of lists means that they aren’t as fast as tuples 7/21/2017 14Swarup Kr Ghosh
  • 15.  append: >>> li = [1, 11, 3, 4, 5] >>> li.append(‘a’) # Our first exposure to method syntax >>> li [1, 11, 3, 4, 5, ‘a’]  insert: >>> li.insert(2, ‘i’) >>>li [1, 11, ‘i’, 3, 4, 5, ‘a’]  extend: >>> li.extend([9, 8, 7]) >>>li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7] 7/21/2017 15Swarup Kr Ghosh
  • 16.  + creates a fresh list (with a new memory reference)  extend operates on list ‘li’ in place >>> li.extend([9, 8, 7]) >>>li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]  Confusing: extend vs append ◦ Extend takes a list as an argument ◦ Append takes a singleton as an argument >>> li.append([10, 11, 12]) >>> li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]] 7/21/2017 16Swarup Kr Ghosh
  • 17. a 1 2 3 b a 1 2 3 b 4 a = [1, 2, 3] a.append(4) b = a a 1 2 3 7/21/2017 17Swarup Kr Ghosh
  • 18. >>> li = [‘a’, ‘b’, ‘c’, ‘b’]  Index: >>> li.index(‘b’) # index of first occurrence 1  Count: >>> li.count(‘b’) # number of occurrences 2  Remove: >>> li.remove(‘b’) # remove first occurrence >>> li [‘a’, ‘c’, ‘b’] 7/21/2017 18Swarup Kr Ghosh
  • 19. >>> li = [5, 2, 6, 8]  Reverse: >>> li.reverse() # reverse the list >>> li [8, 6, 2, 5]  Sort: >>> li.sort() # sort the list >>> li [2, 5, 6, 8] >>> li.sort(some_function) # sort in place using user-defined comparison 7/21/2017 19Swarup Kr Ghosh
  • 20.  Lists slower but more powerful than tuples ◦ Lists can be modified, and they have lots of handy operations we can perform on them ◦ Tuples are immutable and have fewer features  To convert between tuples and lists use the list() and tuple() functions: ◦ li = list(tu) ◦ tu = tuple(li) 7/21/2017 20Swarup Kr Ghosh
  • 21. Matrix: >>> m=[[1,2,3], [4,5,6], [7,8,9]] >>> m [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> n=[[1,1,1], [1,1,1], [1,1,1]] >>> n [[1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> m+n [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 1, 1], [1, 1, 1], [1, 1, 1]] #Concatination not addition 7/21/2017 21Swarup Kr Ghosh
  • 22.  cross products: >>> vec1 = [2,4,6] >>> vec2 = [4,3,-9] >>> [x*y for x in vec1 for y in vec2] [8,6,-18, 16,12,-36, 24,18,-54] >>> [x+y for x in vec1 and y in vec2] [6,5,-7,8,7,-5,10,9,-3] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8,12,-54] 7/21/2017 22Swarup Kr Ghosh
  • 23.  can also use if: >>> vec1 = [2,4,6] >>> [3*x for x in vec1 if x > 3] [12, 18] >>> [3*x for x in vec1 if x < 2] [] 7/21/2017 23Swarup Kr Ghosh
  • 24.  Dictionaries store a mapping between a set of keys and a set of values ◦ Keys can be any immutable type ◦ Accessed by key, not offset position ◦ Unordered collections of arbitrary objects ◦ Variable-length, heterogeneous, and arbitrarily nestable ◦ Tables of object references (hash tables) ◦ Values can be any type ◦ A single dictionary can store values of different types  You can define, modify, view, lookup, and delete the key-value pairs in the dictionary. 7/21/2017 24Swarup Kr Ghosh
  • 25.  Name={key : value,…… }  Name[key]----- Shows value of Dictionary d={'user':'scott','pswd':12345} >>> d['user'] 'scott' >>> d['pswd'] 12345 >>> d['scott'] Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> d['scott'] KeyError: 'scott' 7/21/2017 25Swarup Kr Ghosh
  • 26.  To change values: >>> d['user']='tiger' >>> d {'user': 'tiger', 'pswd': 12345}  To insert another key with value: >>> d['id']=45 >>> d {'user': 'tiger', 'pswd': 12345, 'id': 45}  Keys() method: >>> d.keys() dict_keys(['user', 'pswd', 'id'])  Item() method: >>> d.items() dict_items([('user', 'tiger'), ('pswd', 12345), ('id', 45)]) 7/21/2017 26Swarup Kr Ghosh
  • 27.  Del() method: >>> del(d['user']) >>> d {'pswd': 12345, 'id': 45}  Clear() method: >>> d.clear() >>> d {}  To show all keys and values with specific format: >>> for k in sorted(d.keys()): print('key:',k,'->',d[k]) key: id -> 45 key: pswd -> 12345 key: user -> tiger 7/21/2017 27Swarup Kr Ghosh
  • 28. >>> table = {'1975': 'Holy Grail', '1979': 'Life of Brian', '1983': 'The Meaning of Life'} >>> year = '1983' >>> movie = table[year] >>> movie 'The Meaning of Life‘ >>> for year in table: print(year + 't' + table[year]) 1979 Life of Brian 1975 Holy Grail 1983 The Meaning of Life 7/21/2017Swarup Kr Ghosh 28