PYTHON: LAB8
LIST, TUPLE,
DICTIONARY
Prepared by: eng. Abeer Balbahaith
1) Lists
▪ Like a string, a list is a sequence of values. In a string, the values are characters.
▪ In a list, they can be any type. The values in lists are called elements or sometimes
items.
Programming list
cheeses = ['Cheddar', 'Edam', 'Gouda']
numbers = [17, 123]
empty = []
print(cheeses, numbers, empty)
print(cheeses[0])
numbers[1] = 5
print(numbers)
print('Edam' in cheeses)
print('Brie' in cheeses)
Programming List
for cheese in cheeses:
print(cheese)
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print(numbers)
nested_list=['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
print(len(nested_list))
Operations on List
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c)
d=a*3
print(d)
List Slicing
t = ['a', 'b', 'c', 'd', 'e', 'f']
print(t[1:3])
print(t[:4])
print(t[3:])
List Methods
t = ['a', 'b', 'c']
[Link]('d’)
print(t)
___________________
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
[Link](t2)
print(t1)
List Methods
t = ['d', 'c', 'e', 'b', 'a']
[Link]()
print(t)
___________________
t = ['a', 'b', 'c']
x = [Link](1)
print(t)
print(x)
List Methods
t = ['a', 'b', 'c']
del t[1]
print(t)
___________________________
t = ['a', 'b', 'c']
[Link]('b')
print(t)
List and functions
nums = [3, 41, 12, 9, 74, 15]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
print(sum(nums)/len(nums))
2) Dictionaries
▪ A dictionary is like a list, but more general. In a list, the index positions have to
be integers; in a dictionary, the indices can be (almost) any type. Each item written as
(key:value) pair.
______________________________________________
eng2sp = dict()
print(eng2sp)
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(eng2sp)
print(eng2sp['two’])
print(len(eng2sp))
Dictionaries
Dictionaries
word = ‘school'
d = dict()
for ltr in word:
if ltr not in d:
d[ltr] = 1
else:
d[ltr] = d[ltr] + 1
print(d)
Dictionaries and ‘get’ method
▪ Dictionaries have a method called get that takes a key and a default value. If the key appears in the
dictionary, get returns the corresponding value; otherwise, it returns the default value. For
example:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
print([Link]('jan', 0))
print([Link](‘tim’,2))
Looping and Dictionaries
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
print(key, counts[key])
_________________________________
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
lst = list([Link]())
print(lst)
[Link]()
print(lst)
for key in lst:
print(key, counts[key])
3) Tuples
A tuple is a sequence of values much like a list. But tuple is immutable meaning their
elements cannot be changed, added, or removed once the tuple is created.
Differences between tuples and lists
Programming Tuples
Programming Tuples
Comparing Tuples