SlideShare a Scribd company logo
1 of 30
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

What's hot

Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alexander Pavlenko, Senior Java Developer, "Cassandra into"Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alina Vilk
 
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков АлександрDUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
it-people
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
Lei Kang
 

What's hot (19)

Color picker2
Color picker2Color picker2
Color picker2
 
Five
FiveFive
Five
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alexander Pavlenko, Senior Java Developer, "Cassandra into"Alexander Pavlenko, Senior Java Developer, "Cassandra into"
Alexander Pavlenko, Senior Java Developer, "Cassandra into"
 
Cassandra into
Cassandra intoCassandra into
Cassandra into
 
2013 0928 programming by cuda
2013 0928 programming by cuda2013 0928 programming by cuda
2013 0928 programming by cuda
 
Lispprograaming excercise
Lispprograaming excerciseLispprograaming excercise
Lispprograaming excercise
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков АлександрDUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
DUMP-2013 Serverside - О хранилище “Зебра” - Казаков Александр
 
Everything is composable
Everything is composableEverything is composable
Everything is composable
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Being Google
Being GoogleBeing Google
Being Google
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Python memory management_v2
Python memory management_v2Python memory management_v2
Python memory management_v2
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?
 
3
33
3
 
Dmxedit
DmxeditDmxedit
Dmxedit
 

Similar to Python lec2

python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 

Similar to Python lec2 (20)

Python lec3
Python lec3Python lec3
Python lec3
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptx
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
Chapter 3 Built-in Data Structures, Functions, and Files .pptxChapter 3 Built-in Data Structures, Functions, and Files .pptx
Chapter 3 Built-in Data Structures, Functions, and Files .pptx
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
Day 1c access, select ordering copy.pptx
Day 1c   access, select   ordering copy.pptxDay 1c   access, select   ordering copy.pptx
Day 1c access, select ordering copy.pptx
 
R programming
R programmingR programming
R programming
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examples
 
Day 2 repeats.pptx
Day 2 repeats.pptxDay 2 repeats.pptx
Day 2 repeats.pptx
 
Python
PythonPython
Python
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Interview C++11 code
Interview C++11 codeInterview C++11 code
Interview C++11 code
 

Recently uploaded

Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
Elizabeth Walsh
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 

Recently uploaded (20)

Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdfDiuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 

Python lec2

  • 1. Swarup Kr Ghosh MIS Group IIM Calcutta swarupg1@gmail.com
  • 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