Chap 06 List Dictionary
Chap 06 List Dictionary
Complex Number
10. Python - Lists
○ numbers,
○ strings,
● Accessed by offset
Operation Interpretation
L = [] An empty list
L = [123, 'abc', 1.23, {}] Four items: indexes 0..3
L = ['Bob', 40.0, ['dev', 'mgr']] Nested sublists
L = list('spam') List of an iterable’s items, list of
L = list(range(-4, 4)) successive integers
L[i]
L[i][j] Index, index of index, slice,
L[i:j] length
len(L)
Common list literals and operations (Table 8.1, p.248 – 249)
Operation Interpretation
L1 + L2
Concatenate, repeat
L*3
for x in L: print(x)
Iteration, membership
3 in L
L.append(4)
L.extend([5,6,7]) Methods: growing
L.insert(i, X)
L.index(X)
Methods: searching
L.count(X)
Common list literals and operations (Table 8.1, p.248 – 249)
Operation Interpretation
L.sort()
L.clear()
L.pop(i)
L.remove(X)
del L[i:j]
L[i:j] = []
Common list literals and operations (Table 8.1, p.248 – 249)
Operation Interpretation
4
>>> [1, 2, 3] + [4, 5, 6] #Concatenation
[1, 2, 3, 4, 5, 6]
123
● List comprehensions are a way to build a new list by applying an
● Because lists are sequences, indexing and slicing work the same way
['Spam', 'SPAM!']
● Because you can nest lists and other object types within lists, you will
● When using a list, you can change its contents by assigning to either a
right of the = are inserted into the list on the left, at the place
where the old slice was deleted.
● Insert First
● Insert Last
● Insert at postion
>>> L = [2, 3, 4]
>>> L[:0] = [0, 1] # Insert all at :0, an empty slice at front
>>> L
[0, 1, 2, 3, 4]
>>> L[len(L):] = [5, 6, 7] # Insert all at len(L):, an empty slice at end
>>> L
[0, 1, 2, 3, 4, 5, 6, 7]
>>> L.extend([8, 9, 10]) # Insert all at end, named method
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
● Python list objects also support type-specific method calls, many of which
>>> L = [2, 3, 4]
>>> L.append(0) # Append method call: add item at end
>>> L
[2, 3, 4, 0]
>>> L.sort() # Sort list items
>>> L
[0, 2, 3, 4]
More on sorting lists
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort() # Sort with mixed case
>>> L
['ABD', 'aBe', 'abc']
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key=str.lower) # Normalize to lowercase
>>> L
['abc', 'ABD', 'aBe']
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key=str.lower, reverse=True) # Change sort order
>>> L
['aBe', 'ABD', 'abc']
Other common list methods
>>> L = [1, 2, 3, 4, 5]
>>> L.pop() # Delete and return last item (by default: −1)
5
>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
1
>>> L.insert(1, 'toast') # Insert at position
>>> L
['spam', 'toast', 'eggs', 'ham']
>>> L.remove('eggs') # Delete by value
>>> L
['spam', 'toast', 'ham']
>>> L.pop(1) # Delete by position
'toast'
>>> L.count('spam') # Number of occurrences
1
Other common list operations
● Because lists are mutable, you can use the del statement to delete an
['eggs']
Summary
○ Negative indexing
>>> my_list = [1, "Hello", 3.4] # list with mixed data types
● List Index:
○ We can use the index operator [] to access an item in a list.
○ The index must be an integer. We can't use float or other types, this will result
in TypeError
● Negative indexing
○ Python allows negative indexing for its sequences.
○ The index of -1 refers to the last item, -2 to the second last item and so on.
List Slicing in Python
● We can also use + operator to combine two lists. This is also called
concatenation.
● We can delete one or more items from a list using the Python del statement. It
can even delete the list entirely.
● We can use remove() to remove the given item or pop() to remove an item at the
given index.
● The pop() method removes and returns the last item if the index is not provided.
This helps us implement lists as stacks (first in, last out data structure).
● And, if we have to empty the whole list, we can use the clear() method.
● Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
Exercise 1.0
● Write a Python code in terminal or script file to sum all the items in a list.
● Write Python code in terminal or script file to sum all if element is numeric
unordered collections;
“id” “N19CQCN”
“code” “01”
“start” “2019”
“students”
Nested Keys Nested Keys Values
“sv-1” “firstName
“John”
”
“sv-2” “lastName
“Doe”
”
“idStudent
“N19001”
”
“sv-n” “birthDay” “1998-01-01”
Difference between List and Dictionary:
List Dictionary
List is a collection of index values pairs Dictionary is a hashed structure of key and
as that of array in c++. value pairs.
The indices of list are integers starting The keys of dictionary can be of any data type.
from 0.
The elements are accessed via indices. The elements are accessed via key-values.
The order of the elements entered are There is no guarantee for maintaining order.
maintained.
Common dictionary literals and operations (T.8.2, p.260-261)
Operation Interpretation
D = {} Empty dictionary
D = dict(name='Bob', age=40)
D['name']
Indexing by key
E['cto']['age']
Common dictionary literals and operations (T.8.2, p.260-261)
Operation Interpretation
Operation Interpretation
D.setdefault(key, default?)
● You create dictionaries with literals and store and access items by key
with indexing:
>>> D
True
● Dictionaries, like lists, are mutable, so you can change, expand, and shrink
● The del statement works here, too; it deletes the entry associated with the key
specified as an index.
>>> D
{'eggs': 3, 'spam': 2, 'ham': 1}
>>> D
>>> D
● The dictionary values and items methods return all of the dictionary’s values
● Along with keys, these are useful in loops that need to step through
>>> list(D.values())
[3, 2, 1]
>>> list(D.items())
88
● The update method provides something similar to concatenation for
● It merges the keys and values of one dictionary into another, blindly
>>> D.update(D2)
>>> D
● The dictionary pop method deletes a key from a dictionary and returns the
value it had.
● It’s similar to the list pop method, but it takes a key instead of an optional
position.
pop a dictionary by key
>>> D
>>> D.pop('muffin')
5
>>> D.pop('toast') # Delete and return from a key
4
>>> D
'dd'
>>> L
'bb'
>>> L
['aa', 'cc']
Example: Monty Python movie database
● Creates a simple in-memory Monty Python movie database, as a table that
maps movie release date years (the keys) to movie titles (the values). As
coded, you fetch movie names by indexing on release year strings:
● While the values can be of any data type and can repeat, keys
must be of immutable type (string, number or tuple with
immutable elements) and must be unique.
We can add new items or change the value of existing items using an
assignment operator.
● If the key is already present, then the existing value gets updated. In case
the key is not present, a new (key: value) pair is added to the dictionary.
Removing elements from Dictionary
● All the items can be removed at once, using the clear() method.
● Write a Python program to convert them into a dictionary in a way that item
from list1 is the key and item from list2 is the value
>>> sampleDict = {
… "class": {
… "student": {
… "name": "Mike",
… "marks": {
… "physics": 70,
… "history": 80
… }
… }
… }
…}
Exercise 3.0
Expected output: