SlideShare a Scribd company logo
Lists, Tuples, Sets, Dicts
5/23/2015
List
General purpose
Most widely used data structure
Grow and shrink size as needed
Sequence type
Sortable
Tuple
Immutable (can’t add/change)
Useful for fixed data
Faster than Lists
Sequence type
Set
Store non-duplicate items
Very fast access vs Lists
Math Set ops (union, intersect)
Unordered
Dict
Key/Value pairs
Associative array, like Java HashMap
Unordered
SEQUENCES (String, List, Tuple)
• indexing: x[6]
• slicing: x[1:4]
• adding/concatenating: +
• multiplying: *
• checking membership: in/not in
• iterating for i in x:
• len(sequence1)
• min(sequence1)
• max(sequence1)
• sum(sequence1[1:3]])
• sorted(list1)
• sequence1.count(item)
• sequence1.index(item)
• indexing
– Access any item in the sequence using its index
x = 'frog'
print (x[3]) # prints 'g'
String
x = ['pig', 'cow', 'horse']
print (x[1]) # prints 'cow'
List
SEQUENCES
String List Tuple
• slicing
– Slice out substrings, sublists, subtuples using indexes
[start : end+1 : step]
Code Result Explanation
x[1:4] 'omp' Items 1 to 3
x[1:6:2] 'opt' Items 1, 3, 5
x[3:] 'puter' Items 3 to end
x[:5] 'compu' Items 0 to 4
x[-1] 'r' Last item
x[-3:] 'ter' Last 3 items
x[:-2] 'comput' All except last 2 items
x = 'computer'
SEQUENCES
String List Tuple
• adding / concatenating
– Combine 2 sequences of the same type using +
x = 'horse' + 'shoe'
print (x) # prints 'horseshoe'
String
x = ['pig', 'cow'] + ['horse']
print (x) # prints ['pig', 'cow', 'horse']
List
SEQUENCES
String List Tuple
• multiplying
– Multiply a sequence using *
x = ‘bug' * 3
print (x) # prints ‘bugbugbug'
String
x = [8, 5] * 3
print (x) # prints [8, 5, 8, 5, 8, 5]
List
SEQUENCES
String List Tuple
• checking membership
– Test whether an item is in or not in a sequence
x = 'bug'
print ('u' in x) # prints True
String
x = ['pig', 'cow', 'horse']
print ('cow' not in x) # prints False
List
SEQUENCES
String List Tuple
• iterating
– Iterate through the items in a sequence
x = [7, 8, 3]
for item in x:
print (item * 2) # prints 14, 16, 6
Item
x = [7, 8, 3]
for index, item in enumerate(x):
print (index, item) # prints 0 7, 1 8, 2 3
Index & Item
SEQUENCES
String List Tuple
• number of items
– Count the number of items in a sequence
x = 'bug'
print (len(x)) # prints 3
String
x = ['pig', 'cow', 'horse']
print (len(x)) # prints 3
List
SEQUENCES
String List Tuple
• minimum
– Find the minimum item in a sequence lexicographically
– alpha or numeric types, but cannot mix types
x = 'bug'
print (min(x)) # prints 'b'
String
x = ['pig', 'cow', 'horse']
print (min(x)) # prints 'cow'
List
SEQUENCES
String List Tuple
• maximum
– Find the maximum item in a sequence
– alpha or numeric types, but cannot mix types
x = 'bug'
print (max(x)) # prints 'u'
String
x = ['pig', 'cow', 'horse']
print (max(x)) # prints 'pig'
List
SEQUENCES
String List Tuple
• sum
– Find the sum of items in a sequence
– entire sequence must be numeric type
x = [5, 7, 'bug‘]
print (sum(x)) # error!
String -> Error
x = [2, 5, 8, 12]
print (sum(x)) # prints 27
print (sum(x[-2:])) # prints 20
List
SEQUENCES
String List Tuple
• sorting
– Returns a new list of items in sorted order
– Does not change the original list
x = 'bug'
print (sorted(x))# prints ['b', 'g', 'u']
String
x = ['pig', 'cow', 'horse']
print (sorted(x)) # prints ['cow', 'horse', 'pig']
List
SEQUENCES
String List Tuple
• count (item)
– Returns count of an item
x = 'hippo'
print (x.count('p')) # prints 2
String
x = ['pig', 'cow', 'horse', 'cow']
print (x.count('cow')) # prints 2
List
SEQUENCES
String List Tuple
• index (item)
– Returns the index of the first occurrence of an item
x = 'hippo'
print (x.index('p')) # prints 2
String
x = ['pig', 'cow', 'horse', 'cow']
print (x.index('cow')) # prints 1
List
SEQUENCES
String List Tuple
• unpacking
– Unpack the n items of a sequence into n variables
x = ['pig', 'cow', 'horse']
a, b, c = x # now a is 'pig'
# b is 'cow',
# c is 'horse'
Note:
The number of variables must exactly match the length of the list.
SEQUENCES
String List Tuple
LISTS
All operations from Sequences, plus:
• constructors:
• del list1[2] delete item from list1
• list1.append(item) appends an item to list1
• list1.extend(sequence1) appends a sequence to list1
• list1.insert(index, item) inserts item at index
• list1.pop() pops last item
• list1.remove(item) removes first instance of
item
• list1.reverse() reverses list order
• list1.sort() sorts list in place
LISTS
• constructors – creating a new list
LISTS
x = list()
x = ['a', 25, 'dog', 8.43]
x = list(tuple1)
List Comprehension:
x = [m for m in range(8)]
resulting list: [0, 1, 2, 3, 4, 5, 6, 7]
x = [z**2 for z in range(10) if z>4]
resulting list: [25, 36, 49, 64, 81]
• delete
– Delete a list or an item from a list
x = [5, 3, 8, 6]
del(x[1]) # [5, 8, 6]
del(x) # deletes list x
LISTS
• append
– Append an item to a list
x = [5, 3, 8, 6]
x.append(7) # [5, 3, 8, 6, 7]
LISTS
• extend
– Append an sequence to a list
x = [5, 3, 8, 6]
y = [12, 13]
x.extend(y) # [5, 3, 8, 6, 7, 12, 13]
LISTS
• insert
– Insert an item at given index x.insert(index, item)
x = [5, 3, 8, 6]
x.insert(1, 7) # [5, 7, 3, 8, 6]
x.insert(1,['a','m']) # [5, ['a', 'm'], 7, 3, 8,
6]
LISTS
• pop
– Pops last item off the list, and returns item
x = [5, 3, 8, 6]
x.pop() # [5, 3, 8]
# and returns the 6
print(x.pop()) # prints 8
# x is now [5, 3]
LISTS
• remove
– Remove first instance of an item
x = [5, 3, 8, 6, 3]
x.remove(3) # [5, 8, 6, 3]
LISTS
• reverse
– Reverse the order of the list
x = [5, 3, 8, 6]
x.reverse() # [6, 8, 3, 5]
LISTS
• sort
– Sort the list in place
x = [5, 3, 8, 6]
x.sort() # [3, 5, 6, 8]
Note:
sorted(x) returns a new sorted list without changing the original list x.
x.sort() puts the items of x in sorted order (sorts in place).
LISTS
TUPLES
• Support all operations for Sequences
• Immutable, but member objects may be mutable
• If the contents of a list shouldn’t change, use a tuple
to prevent items from accidently being added,
changed or deleted
• Tuples are more efficient than lists due to Python’s
implementation
TUPLES
• constructors – creating a new tuple
TUPLES
x = () # no-item tuple
x = (1,2,3)
x = 1, 2, 3 # parenthesis are optional
x = 2, # single-item tuple
x = tuple(list1) # tuple from list
• immutable
– But member objects may be mutable
x = (1, 2, 3)
del(x[1]) # error!
x[1] = 8 # error!
x = ([1,2], 3) # 2-item tuple: list and int
del(x[0][1]) # ([1], 3)
TUPLES
• constructors – creating a new set
SETS
x = {3,5,3,5} # {5, 3}
x = set() # empty set
x = set(list1) # new set from list
# strips duplicates
Set Comprehension:
x = {3*x for x in range(10) if x>5}
resulting set: {18, 21, 24, 27} but in random order
SETS
Description Code
Add item to set x x.add(item)
Remove item from set x x.remove(item)
Get length of set x len(x)
Check membership in x
item in x
item not in x
Pop random item from set x x.pop()
Delete all items from set x x.clear()
• basic set operations
• standard mathematical set operations
SETS
Set Function Description Code
Intersection AND set1 & set2
Union OR set1 | set2
Symmetric Difference XOR set1 ^ set2
Difference In set1 but not in set2 set1 – set2
Subset set2 contains set1 set1 <= set2
Superset set1 contains set2 set1 >= set2
• constructors – creating a new dict
DICTIONARIES
x = {'pork':25.3, 'beef':33.8, 'chicken':22.7}
x = dict([('pork', 25.3),('beef', 33.8),('chicken', 22.7)])
x = dict(pork=25.3, beef=33.8, chicken=22.7)
Description Code
Add or change item in dict x x['beef'] = 25.2
Remove item from dict x del x['beef']
Get length of dict x len(x)
Check membership in x
(only looks in keys, not values)
item in x
item not in x
Delete all items from dict x x.clear()
Delete dict x del x
• basic dict operations
DICTIONARIES
• accessing keys and values in a dict
DICTIONARIES
x.keys() # returns list of keys in x
x.values() # returns list of values in x
x.items() # returns list of key-value tuple pairs in x
item in x.values() # tests membership in x: returns boolean
• iterating a dict
DICTIONARIES
for key in x: # iterate keys
print(key, x[key]) # print all key/value pairs
for k, v in x.items(): # iterate key/value pairs
print(k, v) # print all key/value pairs
Note:
Entries in a dict are in random order.

More Related Content

Similar to Intro Python Data Structures.pptx Intro Python Data Structures.pptx (20)

Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptxModulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
NikhilKumar528311
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.pptComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
Python introduction data structures lists etc
Python introduction data structures lists etcPython introduction data structures lists etc
Python introduction data structures lists etc
ssuser26ff68
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘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
 
UNIT III_Python Programming_aditya COllege
UNIT III_Python Programming_aditya COllegeUNIT III_Python Programming_aditya COllege
UNIT III_Python Programming_aditya COllege
Ramanamurthy Banda
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Python data structures
Python data structuresPython data structures
Python data structures
Harry Potter
 
Python data structures
Python data structuresPython data structures
Python data structures
Tony Nguyen
 
Python data structures
Python data structuresPython data structures
Python data structures
Young Alista
 
Python data structures
Python data structuresPython data structures
Python data structures
James Wong
 
Python data structures
Python data structuresPython data structures
Python data structures
Luis Goldster
 
Python data structures
Python data structuresPython data structures
Python data structures
Fraboni Ec
 
fundamental of python --- vivek singh shekawat
fundamental  of python --- vivek singh shekawatfundamental  of python --- vivek singh shekawat
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
Ch-8.pdf
Ch-8.pdfCh-8.pdf
Ch-8.pdf
R.K.College of engg & Tech
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
ssuser442080
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptxModulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
NikhilKumar528311
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.pptComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
Python introduction data structures lists etc
Python introduction data structures lists etcPython introduction data structures lists etc
Python introduction data structures lists etc
ssuser26ff68
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘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
 
UNIT III_Python Programming_aditya COllege
UNIT III_Python Programming_aditya COllegeUNIT III_Python Programming_aditya COllege
UNIT III_Python Programming_aditya COllege
Ramanamurthy Banda
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Python data structures
Python data structuresPython data structures
Python data structures
Harry Potter
 
Python data structures
Python data structuresPython data structures
Python data structures
Tony Nguyen
 
Python data structures
Python data structuresPython data structures
Python data structures
Young Alista
 
Python data structures
Python data structuresPython data structures
Python data structures
James Wong
 
Python data structures
Python data structuresPython data structures
Python data structures
Luis Goldster
 
Python data structures
Python data structuresPython data structures
Python data structures
Fraboni Ec
 
fundamental of python --- vivek singh shekawat
fundamental  of python --- vivek singh shekawatfundamental  of python --- vivek singh shekawat
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
ssuser442080
 

Recently uploaded (20)

Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Ad

Intro Python Data Structures.pptx Intro Python Data Structures.pptx

  • 1. Lists, Tuples, Sets, Dicts 5/23/2015
  • 2. List General purpose Most widely used data structure Grow and shrink size as needed Sequence type Sortable Tuple Immutable (can’t add/change) Useful for fixed data Faster than Lists Sequence type Set Store non-duplicate items Very fast access vs Lists Math Set ops (union, intersect) Unordered Dict Key/Value pairs Associative array, like Java HashMap Unordered
  • 3. SEQUENCES (String, List, Tuple) • indexing: x[6] • slicing: x[1:4] • adding/concatenating: + • multiplying: * • checking membership: in/not in • iterating for i in x: • len(sequence1) • min(sequence1) • max(sequence1) • sum(sequence1[1:3]]) • sorted(list1) • sequence1.count(item) • sequence1.index(item)
  • 4. • indexing – Access any item in the sequence using its index x = 'frog' print (x[3]) # prints 'g' String x = ['pig', 'cow', 'horse'] print (x[1]) # prints 'cow' List SEQUENCES String List Tuple
  • 5. • slicing – Slice out substrings, sublists, subtuples using indexes [start : end+1 : step] Code Result Explanation x[1:4] 'omp' Items 1 to 3 x[1:6:2] 'opt' Items 1, 3, 5 x[3:] 'puter' Items 3 to end x[:5] 'compu' Items 0 to 4 x[-1] 'r' Last item x[-3:] 'ter' Last 3 items x[:-2] 'comput' All except last 2 items x = 'computer' SEQUENCES String List Tuple
  • 6. • adding / concatenating – Combine 2 sequences of the same type using + x = 'horse' + 'shoe' print (x) # prints 'horseshoe' String x = ['pig', 'cow'] + ['horse'] print (x) # prints ['pig', 'cow', 'horse'] List SEQUENCES String List Tuple
  • 7. • multiplying – Multiply a sequence using * x = ‘bug' * 3 print (x) # prints ‘bugbugbug' String x = [8, 5] * 3 print (x) # prints [8, 5, 8, 5, 8, 5] List SEQUENCES String List Tuple
  • 8. • checking membership – Test whether an item is in or not in a sequence x = 'bug' print ('u' in x) # prints True String x = ['pig', 'cow', 'horse'] print ('cow' not in x) # prints False List SEQUENCES String List Tuple
  • 9. • iterating – Iterate through the items in a sequence x = [7, 8, 3] for item in x: print (item * 2) # prints 14, 16, 6 Item x = [7, 8, 3] for index, item in enumerate(x): print (index, item) # prints 0 7, 1 8, 2 3 Index & Item SEQUENCES String List Tuple
  • 10. • number of items – Count the number of items in a sequence x = 'bug' print (len(x)) # prints 3 String x = ['pig', 'cow', 'horse'] print (len(x)) # prints 3 List SEQUENCES String List Tuple
  • 11. • minimum – Find the minimum item in a sequence lexicographically – alpha or numeric types, but cannot mix types x = 'bug' print (min(x)) # prints 'b' String x = ['pig', 'cow', 'horse'] print (min(x)) # prints 'cow' List SEQUENCES String List Tuple
  • 12. • maximum – Find the maximum item in a sequence – alpha or numeric types, but cannot mix types x = 'bug' print (max(x)) # prints 'u' String x = ['pig', 'cow', 'horse'] print (max(x)) # prints 'pig' List SEQUENCES String List Tuple
  • 13. • sum – Find the sum of items in a sequence – entire sequence must be numeric type x = [5, 7, 'bug‘] print (sum(x)) # error! String -> Error x = [2, 5, 8, 12] print (sum(x)) # prints 27 print (sum(x[-2:])) # prints 20 List SEQUENCES String List Tuple
  • 14. • sorting – Returns a new list of items in sorted order – Does not change the original list x = 'bug' print (sorted(x))# prints ['b', 'g', 'u'] String x = ['pig', 'cow', 'horse'] print (sorted(x)) # prints ['cow', 'horse', 'pig'] List SEQUENCES String List Tuple
  • 15. • count (item) – Returns count of an item x = 'hippo' print (x.count('p')) # prints 2 String x = ['pig', 'cow', 'horse', 'cow'] print (x.count('cow')) # prints 2 List SEQUENCES String List Tuple
  • 16. • index (item) – Returns the index of the first occurrence of an item x = 'hippo' print (x.index('p')) # prints 2 String x = ['pig', 'cow', 'horse', 'cow'] print (x.index('cow')) # prints 1 List SEQUENCES String List Tuple
  • 17. • unpacking – Unpack the n items of a sequence into n variables x = ['pig', 'cow', 'horse'] a, b, c = x # now a is 'pig' # b is 'cow', # c is 'horse' Note: The number of variables must exactly match the length of the list. SEQUENCES String List Tuple
  • 18. LISTS All operations from Sequences, plus: • constructors: • del list1[2] delete item from list1 • list1.append(item) appends an item to list1 • list1.extend(sequence1) appends a sequence to list1 • list1.insert(index, item) inserts item at index • list1.pop() pops last item • list1.remove(item) removes first instance of item • list1.reverse() reverses list order • list1.sort() sorts list in place LISTS
  • 19. • constructors – creating a new list LISTS x = list() x = ['a', 25, 'dog', 8.43] x = list(tuple1) List Comprehension: x = [m for m in range(8)] resulting list: [0, 1, 2, 3, 4, 5, 6, 7] x = [z**2 for z in range(10) if z>4] resulting list: [25, 36, 49, 64, 81]
  • 20. • delete – Delete a list or an item from a list x = [5, 3, 8, 6] del(x[1]) # [5, 8, 6] del(x) # deletes list x LISTS
  • 21. • append – Append an item to a list x = [5, 3, 8, 6] x.append(7) # [5, 3, 8, 6, 7] LISTS
  • 22. • extend – Append an sequence to a list x = [5, 3, 8, 6] y = [12, 13] x.extend(y) # [5, 3, 8, 6, 7, 12, 13] LISTS
  • 23. • insert – Insert an item at given index x.insert(index, item) x = [5, 3, 8, 6] x.insert(1, 7) # [5, 7, 3, 8, 6] x.insert(1,['a','m']) # [5, ['a', 'm'], 7, 3, 8, 6] LISTS
  • 24. • pop – Pops last item off the list, and returns item x = [5, 3, 8, 6] x.pop() # [5, 3, 8] # and returns the 6 print(x.pop()) # prints 8 # x is now [5, 3] LISTS
  • 25. • remove – Remove first instance of an item x = [5, 3, 8, 6, 3] x.remove(3) # [5, 8, 6, 3] LISTS
  • 26. • reverse – Reverse the order of the list x = [5, 3, 8, 6] x.reverse() # [6, 8, 3, 5] LISTS
  • 27. • sort – Sort the list in place x = [5, 3, 8, 6] x.sort() # [3, 5, 6, 8] Note: sorted(x) returns a new sorted list without changing the original list x. x.sort() puts the items of x in sorted order (sorts in place). LISTS
  • 28. TUPLES • Support all operations for Sequences • Immutable, but member objects may be mutable • If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being added, changed or deleted • Tuples are more efficient than lists due to Python’s implementation TUPLES
  • 29. • constructors – creating a new tuple TUPLES x = () # no-item tuple x = (1,2,3) x = 1, 2, 3 # parenthesis are optional x = 2, # single-item tuple x = tuple(list1) # tuple from list
  • 30. • immutable – But member objects may be mutable x = (1, 2, 3) del(x[1]) # error! x[1] = 8 # error! x = ([1,2], 3) # 2-item tuple: list and int del(x[0][1]) # ([1], 3) TUPLES
  • 31. • constructors – creating a new set SETS x = {3,5,3,5} # {5, 3} x = set() # empty set x = set(list1) # new set from list # strips duplicates Set Comprehension: x = {3*x for x in range(10) if x>5} resulting set: {18, 21, 24, 27} but in random order
  • 32. SETS Description Code Add item to set x x.add(item) Remove item from set x x.remove(item) Get length of set x len(x) Check membership in x item in x item not in x Pop random item from set x x.pop() Delete all items from set x x.clear() • basic set operations
  • 33. • standard mathematical set operations SETS Set Function Description Code Intersection AND set1 & set2 Union OR set1 | set2 Symmetric Difference XOR set1 ^ set2 Difference In set1 but not in set2 set1 – set2 Subset set2 contains set1 set1 <= set2 Superset set1 contains set2 set1 >= set2
  • 34. • constructors – creating a new dict DICTIONARIES x = {'pork':25.3, 'beef':33.8, 'chicken':22.7} x = dict([('pork', 25.3),('beef', 33.8),('chicken', 22.7)]) x = dict(pork=25.3, beef=33.8, chicken=22.7)
  • 35. Description Code Add or change item in dict x x['beef'] = 25.2 Remove item from dict x del x['beef'] Get length of dict x len(x) Check membership in x (only looks in keys, not values) item in x item not in x Delete all items from dict x x.clear() Delete dict x del x • basic dict operations DICTIONARIES
  • 36. • accessing keys and values in a dict DICTIONARIES x.keys() # returns list of keys in x x.values() # returns list of values in x x.items() # returns list of key-value tuple pairs in x item in x.values() # tests membership in x: returns boolean
  • 37. • iterating a dict DICTIONARIES for key in x: # iterate keys print(key, x[key]) # print all key/value pairs for k, v in x.items(): # iterate key/value pairs print(k, v) # print all key/value pairs Note: Entries in a dict are in random order.