SlideShare a Scribd company logo
Introduction to Programming
Intro to Python
part 3
Lists
Lists
● A list is an object that holds a collection of objects; it represents a
sequence of data. In that sense, a list is similar to a string, except a
string can hold only characters.
● A list can hold any Python object. A list need not be homogeneous;
that is, the elements of a list do not all have to be of the same type.
3
Ordering
List Ordering
List Slicing
• Retrieving a subset of items
• What are the outputs of
Functions and Methods for Lists
● There are several built-in functions that operate on lists. Here are
some useful ones:
● For example, the following computes the average of the values in a
list L:
●average = sum(L)/len(L)
7
Functions and Methods for Lists
● Here are some list methods:
8
Adding Items
• Need to use method
• List.Append( new_item )
• List.Insert(Index_Position, new_item)
• Does not needs to be next in sequence
• Updating values
• List[ index ] = new_value
Searching Items
• for item_to_search IN list_values
• List.index(item_to_search)
• ValueError if not found
• List.count(item_to_search)
• Occurences of item in list
Concatenation / Multiplier
• List.extend(other_list)
• Adds other_list to end of of List
• +=
• Same as above
• List_Values * num_of_times_to_repear
Removal
• List.remove(item_to_remove)
• Raises ValueError
• List.pop( [index] )
• del keyword
• Clear() method
Sorting
• List.sort()
• Key, reverse
• Sorted( any_iterable)
• Key, reverse
• Difference
• changes current vs returns new
Functions and Methods for Lists
● Important note There is a big difference between list methods and
string methods: String methods do not change the original string, but
list methods do change the original list.
● To sort a list L, just use L.sort() and not L=L.sort(). In fact, the latter
will not work at all.
14
Tuples
Tuples
● A tuple is essentially an immutable list. Below is a list with three elements and a
tuple with three elements:
● Tuples are enclosed in parentheses, though the parentheses are actually
optional.
● Indexing and slicing work the same as with lists.
● As with lists, you can get the length of the tuple by using the len function, and,
like lists, tuples have count and index methods.
● However, since a tuple is immutable, it does not have any of the other methods
that lists have, like sort or reverse, as those change the list.
16
L = [1,2,3]
t = (1,2,3)
Tuples
● One reason why there are both lists and tuples is that in situations where speed
really matters, tuples are generally faster than lists.
● The flexibility of lists comes with a corresponding cost in speed.
● To convert an object into a tuple, use tuple.
● The following example converts a list and a string into tuples:
17
t1 = tuple([1,2,3])
t2 = tuple('abcde')
Packing / Unpacking Tuples
• To extract values of tuples
• Variable, after variable = tuple( first_item, item2 )
• * unpacks tuple to function arguments
• Create functions that return tuples
Sets
Sets, as in Mathematical Sets
• in mathematics, a set is a collection of objects, potentially of many
different types
• in a set, no two elements are identical. That is, a set consists of
elements each of which is unique compared to the other elements
• there is no order to the elements of a set
• a set with no elements is the empty set
Creating a set
Set can be created in one of two ways:
•constructor: set(iterable) where
the argument is iterable
my_set = set('abc')
my_set  {'a', 'b', 'c'}
•shortcut: {}, braces where the elements
have no colons (to distinguish them from
dicts)
my_set = {'a', 'b','c'}
Diverse elements
• A set can consist of a mixture of different types of
elements
my_set = {'a',1,3.14159,True}
• as long as the single argument can be iterated through,
you can make a set of it
no duplicates
• duplicates are automatically removed
my_set = set("aabbccdd")
print(my_set)
 {'a', 'c', 'b', 'd'}
common operators
Most data structures respond to these:
• len(my_set)
• the number of elements in a set
• element in my_set
• boolean indicating whether element is in the set
• for element in my_set:
• iterate through the elements in my_set
Set operators
• The set data structure provides some special operators that
correspond to the operators you learned in middle school.
• These are various combinations of set contents
• These operations have both a method name and a shortcut binary
operator
method: intersection, op: &
a_set=set("abcd") b_set=set("cdef")
a_set & b_set  {'c', 'd'}
b_set.intersection(a_set)  {'c', 'd'}
e f
a b c d
method:difference op:-
a_set=set("abcd") b_set=set("cdef")
a_set – b_set  {'a', 'b'}
b_set.difference(a_set)  {'e', 'f'}
e f
a b c d
method: union, op: |
a_set=set("abcd") b_set=set("cdef")
a_set | b_set  {'a', 'b', 'c', 'd', 'e', 'f'}
b_set.union(a_set)  {'a', 'b', 'c', 'd', 'e',
'f'}
a b c d e f
method: symmetric_difference, op: ^
a_set=set("abcd"); b_set=set("cdef")
a_set ^ b_set  {'a', 'b', 'e', 'f'}
b_set.symmetric_difference(a_set)  {'a', 'b',
'e', 'f'}
e f
a b c d
method: issubset, op: <=
method: issuperset, op: >=
small_set=set("abc"); big_set=set("abcdef")
small_set <= big_set  True
bit_set >= small_set  True
a b c d e f
Other Set Ops
• my_set.add("g")
• adds to the set, no effect if item is in set already
• my_set.clear()
• emptys the set
• my_set.remove("g") versus
my_set.discard("g")
• remove throws an error if "g" isn't there. discard doesn't
care. Both remove "g" from the set
• my_set.copy()
• returns a shallow copy of my_set
Dictionaries
What is a dictionary?
• In data structure terms, a dictionary is better termed an associative
array, associative list or a map.
• You can think if it as a list of pairs, where the first element of the pair,
the key, is used to retrieve the second element, the value.
• We map a key to a value
Key Value pairs
• The key acts as an index to find the associated value.
• Just like a dictionary, you look up a word by its spelling to find the
associated definition
• A dictionary can be searched to locate the value associated with a key
• Key must be immutable
• strings, integers, tuples are fine
• lists are NOT
• Value can be anything
Dictionaries
● To declare a dictionary we enclose it in curly braces, {}.
● Each entry consists of a pair separated by a colon.
● The first part of the pair is called the key and the second is the value.
● The key acts like an index.
● Here is a simple dictionary:
● So in the first pair, 'A':100, the key is 'A', the value is 100, and d['A'] gives 100.
● Keys are often strings, but they can be integers, floats, and many other things as
well. You can mix different types of keys in the same dictionary and different
types of values, too.
35
d = {'A':100, 'B':200}
Functions and Methods for Dictionaries
● To change d['A'] to 400: d['A']=400
● To add a new entry to the dictionary, we can just assign it, like below: d['C']=500
● To delete an entry from a dictionary, use the del operator: del d['A']
● To copy a dictionary, use its copy method. Here is an example: d2 = d.copy()
● The empty dictionary is {}, which is the dictionary equivalent of [] for lists or '' for
strings.
36
d = {'A':100, 'B':200}
Functions and Methods for Dictionaries
● The dict function is another way to create a dictionary.
d = dict([('A',100),('B',300)])
● This creates the dictionary {'A':100,'B':300}. This way of building a
dictionary is useful if your program needs to construct a dictionary
while it is running.
37
Dictionary content methods
• my_dict.items() – all the key/value pairs
• my_dict.keys() – all the keys
• my_dict.values() – all the values
There return what is called a dictionary view.
• the order of the views corresponds
• are dynamically updated with changes
Views are iterable
for key in my_dict:
print key
• prints all the keys
for key,value in my_dict.items():
print key,value
• prints all the key/value pairs
for value in my_dict.values():
print value
• prints all the values

More Related Content

PPTX
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
PPTX
Python PPT.pptx
KanwerpreetSingh1
 
PPTX
Dictionaries and Sets
Munazza-Mah-Jabeen
 
PPTX
Python data structures
kalyanibedekar
 
PPTX
python ..... _
swati463221
 
PPTX
UNIT-3 python and data structure alo.pptx
harikahhy
 
PPTX
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
PDF
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Python PPT.pptx
KanwerpreetSingh1
 
Dictionaries and Sets
Munazza-Mah-Jabeen
 
Python data structures
kalyanibedekar
 
python ..... _
swati463221
 
UNIT-3 python and data structure alo.pptx
harikahhy
 
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 

Similar to Python introduction data structures lists etc (20)

PPT
Tuples, sets and dictionaries-Programming in Python
ssuser2868281
 
DOC
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
PPTX
Learn python - for beginners - part-2
RajKumar Rampelli
 
PPTX
ITS-16163: Module 5 Using Lists and Dictionaries
oudesign
 
PPTX
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
PPTX
Python list tuple dictionary .pptx
miteshchaudhari4466
 
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
PPTX
6Dictionaries and sets in pythonsss.pptx
OkelloBenjamin2
 
PPTX
Basic data structures in python
Celine George
 
PPTX
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
PPTX
dataStructuresInPython.pptx
YashaswiniChandrappa1
 
PPTX
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
PPTX
Datastructures in python
hydpy
 
PDF
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Meha46
 
PPTX
Python - Data Structures
NR Computer Learning Center
 
PDF
python.pdf
wekarep985
 
PPTX
List_tuple_dictionary.pptx
ChandanVatsa2
 
PPTX
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
lokeshgoud13
 
PPTX
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
judyhilly13
 
PPTX
Seventh session
AliMohammad155
 
Tuples, sets and dictionaries-Programming in Python
ssuser2868281
 
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Learn python - for beginners - part-2
RajKumar Rampelli
 
ITS-16163: Module 5 Using Lists and Dictionaries
oudesign
 
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
Python list tuple dictionary .pptx
miteshchaudhari4466
 
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
6Dictionaries and sets in pythonsss.pptx
OkelloBenjamin2
 
Basic data structures in python
Celine George
 
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
dataStructuresInPython.pptx
YashaswiniChandrappa1
 
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
Datastructures in python
hydpy
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Meha46
 
Python - Data Structures
NR Computer Learning Center
 
python.pdf
wekarep985
 
List_tuple_dictionary.pptx
ChandanVatsa2
 
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
lokeshgoud13
 
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
judyhilly13
 
Seventh session
AliMohammad155
 
Ad

Recently uploaded (20)

PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Ad

Python introduction data structures lists etc

  • 3. Lists ● A list is an object that holds a collection of objects; it represents a sequence of data. In that sense, a list is similar to a string, except a string can hold only characters. ● A list can hold any Python object. A list need not be homogeneous; that is, the elements of a list do not all have to be of the same type. 3
  • 6. List Slicing • Retrieving a subset of items • What are the outputs of
  • 7. Functions and Methods for Lists ● There are several built-in functions that operate on lists. Here are some useful ones: ● For example, the following computes the average of the values in a list L: ●average = sum(L)/len(L) 7
  • 8. Functions and Methods for Lists ● Here are some list methods: 8
  • 9. Adding Items • Need to use method • List.Append( new_item ) • List.Insert(Index_Position, new_item) • Does not needs to be next in sequence • Updating values • List[ index ] = new_value
  • 10. Searching Items • for item_to_search IN list_values • List.index(item_to_search) • ValueError if not found • List.count(item_to_search) • Occurences of item in list
  • 11. Concatenation / Multiplier • List.extend(other_list) • Adds other_list to end of of List • += • Same as above • List_Values * num_of_times_to_repear
  • 12. Removal • List.remove(item_to_remove) • Raises ValueError • List.pop( [index] ) • del keyword • Clear() method
  • 13. Sorting • List.sort() • Key, reverse • Sorted( any_iterable) • Key, reverse • Difference • changes current vs returns new
  • 14. Functions and Methods for Lists ● Important note There is a big difference between list methods and string methods: String methods do not change the original string, but list methods do change the original list. ● To sort a list L, just use L.sort() and not L=L.sort(). In fact, the latter will not work at all. 14
  • 16. Tuples ● A tuple is essentially an immutable list. Below is a list with three elements and a tuple with three elements: ● Tuples are enclosed in parentheses, though the parentheses are actually optional. ● Indexing and slicing work the same as with lists. ● As with lists, you can get the length of the tuple by using the len function, and, like lists, tuples have count and index methods. ● However, since a tuple is immutable, it does not have any of the other methods that lists have, like sort or reverse, as those change the list. 16 L = [1,2,3] t = (1,2,3)
  • 17. Tuples ● One reason why there are both lists and tuples is that in situations where speed really matters, tuples are generally faster than lists. ● The flexibility of lists comes with a corresponding cost in speed. ● To convert an object into a tuple, use tuple. ● The following example converts a list and a string into tuples: 17 t1 = tuple([1,2,3]) t2 = tuple('abcde')
  • 18. Packing / Unpacking Tuples • To extract values of tuples • Variable, after variable = tuple( first_item, item2 ) • * unpacks tuple to function arguments • Create functions that return tuples
  • 19. Sets
  • 20. Sets, as in Mathematical Sets • in mathematics, a set is a collection of objects, potentially of many different types • in a set, no two elements are identical. That is, a set consists of elements each of which is unique compared to the other elements • there is no order to the elements of a set • a set with no elements is the empty set
  • 21. Creating a set Set can be created in one of two ways: •constructor: set(iterable) where the argument is iterable my_set = set('abc') my_set  {'a', 'b', 'c'} •shortcut: {}, braces where the elements have no colons (to distinguish them from dicts) my_set = {'a', 'b','c'}
  • 22. Diverse elements • A set can consist of a mixture of different types of elements my_set = {'a',1,3.14159,True} • as long as the single argument can be iterated through, you can make a set of it
  • 23. no duplicates • duplicates are automatically removed my_set = set("aabbccdd") print(my_set)  {'a', 'c', 'b', 'd'}
  • 24. common operators Most data structures respond to these: • len(my_set) • the number of elements in a set • element in my_set • boolean indicating whether element is in the set • for element in my_set: • iterate through the elements in my_set
  • 25. Set operators • The set data structure provides some special operators that correspond to the operators you learned in middle school. • These are various combinations of set contents • These operations have both a method name and a shortcut binary operator
  • 26. method: intersection, op: & a_set=set("abcd") b_set=set("cdef") a_set & b_set  {'c', 'd'} b_set.intersection(a_set)  {'c', 'd'} e f a b c d
  • 27. method:difference op:- a_set=set("abcd") b_set=set("cdef") a_set – b_set  {'a', 'b'} b_set.difference(a_set)  {'e', 'f'} e f a b c d
  • 28. method: union, op: | a_set=set("abcd") b_set=set("cdef") a_set | b_set  {'a', 'b', 'c', 'd', 'e', 'f'} b_set.union(a_set)  {'a', 'b', 'c', 'd', 'e', 'f'} a b c d e f
  • 29. method: symmetric_difference, op: ^ a_set=set("abcd"); b_set=set("cdef") a_set ^ b_set  {'a', 'b', 'e', 'f'} b_set.symmetric_difference(a_set)  {'a', 'b', 'e', 'f'} e f a b c d
  • 30. method: issubset, op: <= method: issuperset, op: >= small_set=set("abc"); big_set=set("abcdef") small_set <= big_set  True bit_set >= small_set  True a b c d e f
  • 31. Other Set Ops • my_set.add("g") • adds to the set, no effect if item is in set already • my_set.clear() • emptys the set • my_set.remove("g") versus my_set.discard("g") • remove throws an error if "g" isn't there. discard doesn't care. Both remove "g" from the set • my_set.copy() • returns a shallow copy of my_set
  • 33. What is a dictionary? • In data structure terms, a dictionary is better termed an associative array, associative list or a map. • You can think if it as a list of pairs, where the first element of the pair, the key, is used to retrieve the second element, the value. • We map a key to a value
  • 34. Key Value pairs • The key acts as an index to find the associated value. • Just like a dictionary, you look up a word by its spelling to find the associated definition • A dictionary can be searched to locate the value associated with a key • Key must be immutable • strings, integers, tuples are fine • lists are NOT • Value can be anything
  • 35. Dictionaries ● To declare a dictionary we enclose it in curly braces, {}. ● Each entry consists of a pair separated by a colon. ● The first part of the pair is called the key and the second is the value. ● The key acts like an index. ● Here is a simple dictionary: ● So in the first pair, 'A':100, the key is 'A', the value is 100, and d['A'] gives 100. ● Keys are often strings, but they can be integers, floats, and many other things as well. You can mix different types of keys in the same dictionary and different types of values, too. 35 d = {'A':100, 'B':200}
  • 36. Functions and Methods for Dictionaries ● To change d['A'] to 400: d['A']=400 ● To add a new entry to the dictionary, we can just assign it, like below: d['C']=500 ● To delete an entry from a dictionary, use the del operator: del d['A'] ● To copy a dictionary, use its copy method. Here is an example: d2 = d.copy() ● The empty dictionary is {}, which is the dictionary equivalent of [] for lists or '' for strings. 36 d = {'A':100, 'B':200}
  • 37. Functions and Methods for Dictionaries ● The dict function is another way to create a dictionary. d = dict([('A',100),('B',300)]) ● This creates the dictionary {'A':100,'B':300}. This way of building a dictionary is useful if your program needs to construct a dictionary while it is running. 37
  • 38. Dictionary content methods • my_dict.items() – all the key/value pairs • my_dict.keys() – all the keys • my_dict.values() – all the values There return what is called a dictionary view. • the order of the views corresponds • are dynamically updated with changes
  • 39. Views are iterable for key in my_dict: print key • prints all the keys for key,value in my_dict.items(): print key,value • prints all the key/value pairs for value in my_dict.values(): print value • prints all the values