List
Examples
• Apple, Banana, Berry, Mango
• Football, Basketball, Throwball, Tennis, Hockey
• Sunrise, Sugar, Cheese, Butter, Pickle, Soap,
Washing Powder, Oil….
• Agra, Delhi, Kashmir, Jaipur, Kolkata…
Introduction
• Contains multiple values that are logically related
• List is a type of mutable sequence in Python
• Each element of a list is assigned a number –
index / position
• Can do indexing, slicing, adding, multiplying, and
checking for membership
• Built-in functions for finding length of a sequence
and for finding its largest and smallest elements
What is a List?
• Most versatile data type in Python
• Comma-separated items can be collected in
square brackets
• Good thing is..
– THE ITEMS IN THE LIST NEED NOT BE OF SAME
TYPE
Creating a list
• Creating an EMPTY • Creating a list with items
list listname = [item1, item2, ….]
listname = [] Example:
Example: Temp = [100, 99.8, 103, 102]
L1 = [] S = [‘15BIT0001’, ‘Achu’, 99.9]
MyList = []
L2 = [1, 2, 3, 4, 5, 6, 7]
Books = []
Course = [‘Python’, ‘C’, ‘C++’,
‘Java’]
Accessing Values
• Using index or indices
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>print (L1[3]) #indexing
>>>4
>>>print (L1[2:5]) #slicing
>>>[3, 4, 5]
Updating Elements
• Update an element in list using index
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>L1[2] = 111
>>>L1
[1, 2, 111, 4, 5, 6]
Deleting Elements
• Delete an element in list using index
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>del L1[4]
>>>L1
[1, 2, 3, 4, 6]
Basic Operations in List
• >>> len([1, 2, 3]) # Length
3
• >>> [1, 2, 3] + [4, 5, 6] # Concatenation
[1, 2, 3, 4, 5, 6]
• >>> ['Ni!'] * 4 # Repetition
['Ni!', 'Ni!', 'Ni!', 'Ni!']
Basic Operations in List
• >>> str([1, 2]) + "34" # Same as "[1, 2]" + "34"
'[1, 2]34'
• >>> [1, 2] + ["3", "4"]
[1, 2, '3', '4‘]
List Iteration
• >>> 3 in [1, 2, 3] # Membership
True
• >>> for x in [1, 2, 3]:
print(x, end=' ')
# Iteration (print x,) ... 1 2 3
List Comprehensions
>>> res = [c * 4 for c in 'SPAM']
# List comprehensions
>>> print(res)
['SSSS', 'PPPP', 'AAAA', 'MMMM']
• expression is functionally equivalent to a for
loop that builds up a list of results manually
• list comprehensions are simpler to code and
likely faster to run today:
List Comprehensions
# List comprehension equivalent ...
>>> res = []
>>> for c in 'SPAM':
res.append(c * 4)
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
Map
• map built-in function applies a function to
items in a sequence and collects all the results
in a new list
• >>> list(map(abs, [−1, −2, 0, 1, 2]))
• # Map a function across a sequence
[1, 2, 0, 1, 2]
Indexing, Slicing
>>> L = ['spam', 'Spam', 'SPAM!']
>>> L[2] # Offsets start at zero
'SPAM!'
>>> L[−2] # Negative: count from the right
'Spam'
>>> L[1:] # Slicing fetches sections
['Spam', 'SPAM!']
Matrixes
• a basic 3 × 3 two-dimensional list-based array:
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• With one index, you get an entire row (really, a
nested sublist), and with two, you get an item
within the row:
>>> matrix[1]
[4, 5, 6]
Matrixes
>>> matrix[1][1]
5
>>> matrix[2][0]
7
>>> matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
>>> matrix[1][1]
5
Insertion, Deletion and Replacement
>>> L = [1, 2, 3]
>>> L[1:2] = [4, 5] # Replacement/insertion
>>> L
[1, 4, 5, 3]
>>> L[1:1] = [6, 7] # Insertion (replace nothing)
>>> L
[1, 6, 7, 4, 5, 3]
>>> L[1:2] = [] # Deletion (insert nothing)
>>> L
[1, 7, 4, 5, 3]
Insertion, Deletion and Replacement
>>> L = [1]
>>> L[:0] = [2, 3, 4]
# Insert all at :0, an empty slice at front
>>> L
[2, 3, 4, 1]
>>> L[len(L):] = [5, 6, 7]
# Insert all at len(L):, an empty slice at end
>>> L
[2, 3, 4, 1, 5, 6, 7]
List method calls
>>> L = ['eat', 'more', 'SPAM!']
>>> L.append('please')
# Append method call: add item at end
>>> L
['eat', 'more', 'SPAM!', 'please']
>>> L.sort() # Sort list items ('S' < 'e')
>>> L
['SPAM!', 'eat', 'more', 'please']
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']
More on Sorting Lists
>>> L.sort(key=str.lower, reverse=True)
# Change sort order
>>> L ['aBe', 'ABD', 'abc']
Other common list methods
>>> L = [1, 2]
>>> L.extend([3, 4, 5])
# Add many items at end (like in-place +)
>>> L [1, 2, 3, 4, 5]
>>> L.pop()
# Delete and return last item
5
Other common list methods
L=[4, 3, 2, 1]
L.reverse()
print(L)
print(list(reversed(L)) )
# In-place reversal method
# Reversal built-in with a result (iterator)
[1, 2, 3, 4]
Other common list methods
>>> L = ['spam', 'eggs', 'ham']
>>> L.index('eggs') # Index of an object (search/find)
1
>>> L.insert(1, 'toast') # Insert at position
>>> L
['spam', 'toast', 'eggs', 'ham']
>>> L.remove('eggs') # Delete by value
>>> L
['spam', 'toast', 'ham']
Other common list methods
>>> L.pop[1] # Delete by position 'toast'
>>> L
['spam', 'ham']
>>> L.count('spam') # Number of occurrences 1
1
Other common list methods
>>> L = ['spam', 'eggs', 'ham', 'toast']
>>> del L[0] # Delete one item
>>> L ['eggs', 'ham', 'toast']
>>> del L[1:] # Delete an entire section
>>> L # Same as L[1:] = []
['eggs‘]
Other common list methods
>>> L = ['Already', 'got', 'one']
>>> L[1:] = []
>>> L
['Already']
>>> L[0] = []
>>> L
[[]]
Hence…
• A list is a sequence of items stored as a single
object.
• Items in a list can be accessed by indexing, and
sub lists can be accessed by slicing.
• Lists are mutable; individual items or entire slices
can be replaced through assignment statements.
• Lists support a number of convenient and
frequently used methods.
• Lists will grow and shrink as needed.
Python Programming, 1/e 29
Strings and Lists
>>> S = 'spammy'
>>> L = list(S)
>>> L
['s', 'p', 'a', 'm', 'm', 'y']
>>> L[3] = 'x' # Works for lists, not strings
>>> L[4] = 'x‘
>>> L
['s', 'p', 'a', 'x', 'x', 'y']
>>> S = S.join(L) #uses ‘’ for joining elements of list
>>> S
'spaxxy‘
Strings and Lists
>>> 'SPAM'.join(['eggs', 'sausage', 'ham', 'toast'])
'eggsSPAMsausageSPAMhamSPAMtoast‘
# uses ‘SPAM’ for joining elements of list
>>> line = 'aaa bbb ccc'
>>> cols = line.split()
>>> cols
['aaa', 'bbb', 'ccc']
Tuples
Tuples
Sequence of immutable Python objects
Tuples cannot be changed like lists, and tuples use
parenthesis, whereas lists use square brackets.
Creating a tuple is as simple as putting different
comma-separated values.
Optionally you can put these comma-separated
values between parenthesis also.
For example −
tup1 = ('test1', 'test2', 100, 15);
tup2 = (9,2,3,4,1);
tup3 = ('S','a','t','i','s','h')
print(tup1,tup2,tup3)
empty tuple −
tup1 = ();
To write a tuple containing a single value you have to
include a comma −
a = (50) # an integer
tup1 = (50,); # tuple containing an integer
tuple indices start at 0
tup1= (“chemistry”, “physics”, “Biology”)
print ("tup1[0]: ", tup1[0]) # print physics
tup2 = (1,2,3,4,5)
print ("tup2[1:5]: ", tup2[1:5]) # print (2,3,4,5)
Tuples in Action
>>> (1, 2) + (3, 4) # Concatenation
(1, 2, 3, 4)
>>> (1, 2) * 4 # Repetition
(1, 2, 1, 2, 1, 2, 1, 2)
>>> T = (1, 2, 3, 4) # Indexing, slicing
>>> T[0], T[1:3]
(1, (2, 3))
Sorted method in Tuples
>>> tmp = ['aa', 'bb', 'cc', ‘ee’ , 'dd']
>>> T = tuple(tmp) # Make a tuple from the list's items
>>> T
('aa', 'bb', 'cc', 'dd')
>>> sorted(T)
['aa', 'bb', 'cc', 'dd‘]
List comprehensions can also be used with tuples.
The following, for example, makes a list from a tuple,
adding 20 to each item along the way:
T = (1, 2, 3, 4, 5)
for x in T:
x=x+20
print(x)
Equivalent to:
>>>L = []
>>>for x in L:
L.append(x+20)
>>> L
[21, 22, 23, 24, 25]
Index method can be used to find the position of
particular value in the tuple.
>>> T = (1, 2, 3, 2, 4, 2)
>>> T.index(2) # Offset of first appearance of 2
1
>>> T.index(2, 2) # Offset of appearance after offset 2
3
>>> T.count(2) # How many 2s are there?
3
Nested Tuples
>>> T = (1, [2, 3], 4)
>>> T[1] = 'spam' # fails: can't change
tuple itself TypeError: object doesn't support item
assignment
T = (1, [2, 3], 4)
T[1][0] = 'spam'
# Works: can change mutables inside
T
(1, ['spam', 3], 4)
>>> bob = ('Bob', 40.5, ['dev', 'mgr'])
# Tuple record
>>> bob
('Bob', 40.5, ['dev', 'mgr'])
>>> bob[0], bob[2] # Access by position
('Bob', ['dev', 'mgr'])
Converts a list into a tuple
tuple(seq)
t2=tuple([2,4])
>>> t2
(2, 4)
Introduction to Dictionaries
• Pair of items
• Each pair has key and value
• Keys should be unique
• Key and value are separated by :
• Each pair is separated by ,
Example:
dict = {‘Alice’ : 1234, ‘Bob’ : 1235}
Properties of Dictionaries
• unordered mutable collections;
• items are stored and fetched by key,
• Accessed by key, not offset position
• Unordered collections of arbitrary objects
• Variable-length, heterogeneous, and
arbitrarily nestable
Creating a Dictionary
• Creating an EMPTY • Creating a dictionary with items
dictionary dictname = {key1:val1, key2:val2,
dictname = {} ….}
Example: Example:
Dict1 = {} MyDict = { 1 : “Chocolate”, 2 :
MyDict = {} “Icecream”}
Books = {} MyCourse = {“MS” : “Python”, “IT” :
“C”,
‘CSE’ : ‘C++’, ‘MCA’ : ‘Java’}
MyCircle = {“Hubby”:9486028245,
“Mom”:9486301601}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
print(x)
x = thisdict.get("model")
• thisdict["year"] = 2018
print(thisdict)
•
Accessing Values
• Using keys within square brackets
>>> print MyDict[1]
‘Chocholate’
>>> print MyCourse[‘CSE’]
‘C++’
Updating Elements
• update by adding a new item (key-value) pair
• modify an existing entry
>>>MyDict[1] = ‘Pizza’
>>>MyCourse[‘MCA’] = ‘UML’
Deleting Elements
• remove an element in a dictionary using the
key
>>>del MyCourse[‘IT’]
• remove all the elements
>>>MyCourse.clear()
• delete the dictionary
>>>del MyCourse
Basic Operations
>>> D = {'spam': 2, 'ham': 1, 'eggs': 3}
>>> len(D) # Number of entries in dictionary 3
>>> 'ham' in D # Key membership test
True
>>> list(D.keys()) # Create a new list of D's keys
['eggs', 'spam', 'ham']
Basic Operations
>>> list(D.values()) [3, 2, 1]
>>> list(D.items()) [('eggs', 3), ('spam', 2), ('ham', 1)]
>>> D.get('spam') # A key that is there
>>> print(D.get('toast')) # A key that is missing
None
Update Method
>>> D
{'eggs': 3, 'spam': 2, 'ham': 1}
>>> D2 = {'toast':4, 'muffin':5}
>>> D.update(D2)
>>> D
{'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1}
#unordered
Pop Method
Delete and return value for a given key
>>> D = {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2,
'ham': 1}
>>> D.pop('muffin')
5
>>> D.pop('toast‘)
4
>>> D
{'eggs': 3, 'spam': 2, 'ham': 1}
List vs Dictionary
>>> L = []
>>> L[99] = 'spam'
Traceback (most recent call last): File "<stdin>", line
1, in ? IndexError: list assignment index out of
range
>>>D = {}
>>> D[99] = 'spam'
>>> D[99] 'spam'
>>> D {99: 'spam'}
Nesting in dictionaries
>>> jobs = []
>>> jobs.append('developer')
>>> jobs.append(‘manager‘)
rec = {}
>>> rec['name'] = 'Bob'
>>> rec['age'] = 40.5
>>> rec['job'] = jobs
Nesting in dictionaries
>>> rec
{'name': 'Bob', 'age': 40.5, 'job': ['developer',
'manager']}
Nesting in dictionaries
>>> rec['name']
'Bob'
>>> rec['job']
['developer', 'manager']
>>> rec['job'][1]
'manager’
Other Ways to Make Dictionaries
D = {'name': 'Bob', 'age': 40}
D = {} # Assign by keys dynamically
D['name'] = 'Bob'
D['age'] = 40
# Creating a dictionary by assignment
dict(name='Bob', age=40)
# Creating dictionary with tuples form
dict([('name', 'Bob'), ('age', 40)])
Comprehensions in Dictionaries
>>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> D = {x: x ** 2 for x in [1, 2, 3, 4]}
# Or: range(1, 5)
Comprehensions in Dictionaries
>>> D
{1: 1, 2: 4, 3: 9, 4: 16}
>>> D = {c: c * 4 for c in 'SPAM'}
>>> D
{'S': 'SSSS', 'P': 'PPPP', 'A': 'AAAA', 'M': 'MMMM'}
Comprehensions in Dictionaries
>>> D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS',
'HAM']}
>>> D
{'eggs': 'EGGS!', 'spam': 'SPAM!', 'ham': 'HAM!'}
Initializing Dictionaries
# Initialize dict from keys
>>> D = dict.fromkeys(['a', 'b', 'c'], 0)
>>> D {'b': 0, 'c': 0, 'a': 0}
# Same, but with a comprehension
>>> D = {k:0 for k in ['a', 'b', 'c']}
>>> D {'b': 0, 'c': 0, 'a': 0}
Initializing Dictionaries
# Initialize dict from keys
>>> D = dict.fromkeys(['a', 'b', 'c'], 0)
>>> D {'b': 0, 'c': 0, 'a': 0}
Initializing Dictionaries
# Comprehension
>>> D = {k: None for k in 'spam'}
>>> D {'s': None, 'p': None, 'a': None, 'm': None}
Dictionary methods
➢ <dict>.items()
– displays the items in the dictionary (pair of keys and values)
➢ <dict>.keys()
- display the keys in the dictionary
➢ <dict>.values()
– displays the values in the dictionary
➢ <dict>.pop()
– removes the last item from the dictionary
➢ <dict2> = <dict1>.copy()
– copies the items from dict1 to dict2
➢ <dict>.clear()
– removes all the items from the dictionary
Dictionaries can replace elif ladder/switch-case
print ({1:’one’,2:’two’,3:’three’,4:’four’,5:’five’}
[choice])
if choice = 3 then the code prints three
Other methods
➢ str(dict)
– produces printable string representation of a dictionary
➢ len(dict)
– returns the number of items in the dictionary
Exercise 1:
Write a program to maintain a telephone
directory of the employees of an organization. If
the employee has more than one number store
all the numbers. Write a program to print the
mobile numbers given full or part of the name
of the employee. Eg: Given name of the
employee as ‘John’ the program must print
phone numbers of ‘John Paul’ and ‘Michel John’.
Exercise 2:
Write a program to store the name
of the players against each of a 20-
20 cricket team. The program should
print the name of the players given
the team name.