0% found this document useful (0 votes)
4 views30 pages

Computer Programming - Lecture 9

This document provides an overview of lists and dictionaries in Python, detailing their characteristics, operations, and usage examples. It explains how to create, modify, and access elements in lists and dictionaries, as well as introduces tuples and their operations. Key concepts include indexing, slicing, appending, and using the 'in' operator for membership testing.

Uploaded by

Panda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

Computer Programming - Lecture 9

This document provides an overview of lists and dictionaries in Python, detailing their characteristics, operations, and usage examples. It explains how to create, modify, and access elements in lists and dictionaries, as well as introduces tuples and their operations. Key concepts include indexing, slicing, appending, and using the 'in' operator for membership testing.

Uploaded by

Panda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Computer

Programming: Lecture
9
Outline
• List
• Dictionaries
List
A list is a built-in data type in Python used to store collections of items.

A List can contain elements of different data types including other lists.

my_list = [1,2,3,4]
names =
[“Abebe”,”Bekele”,”Ayalew”]
Lists
Characteristics of lists:
- Lists can be indexed
- Lists are mutable
- List can contain heterogeneous collection of items
List
Indexing - elements of list have indexes starting from 0 to the length of
the list minus 1.

>>> my_list = [1,2,3,4]


>>> my_list[0] => 1
>>> my_list[1] = > 2
>>> my_list[2] => 3
>>> my_list[3] => 4
List
Negative indexes: you can also indexes lists with negative indexes.
The index of the last element is -1, the second last is -2 and so on.

>>> my_list = [1,2,3,4]


>>> my_list[-1] => 4
>>> my_list[-2] => 3
>>> my_list[-3] => 2
>>> my_list[-4] => 1
List
Slicing: like strings you can also slice lists with indexes.
Syntax:
- mylist[start index: end index: step]
- The start index default is 0
- The end index default is length of the list - 1
- The step default is 1
- Slicing retrieves elements from the start index to end index - 1
List
Slicing examples:
>>> my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_list[0:5] => [0, 1, 2, 3, 4]
>>> my_list[:5] => [0, 1, 2, 3, 4]
>>> my_list[5:] => [5, 6, 7, 8, 9, 10]
>>> my_list[::2] => [0, 2, 4, 6, 8, 10]
>>> my_list[::-1] => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> my_list[8:0:-2] =>[8, 6, 4, 2]
>>> my_list[8::-2] => [8, 6, 4, 2,0]
Lists
Modifying lists - lists are mutable and the elements of a list can be modified.
>>> my_list = [1,2,3,4,5]
>>> my_list[1] = 6
>>> my_list => [1,6,3,4,5]
List Operations
Adding element to a list:
- Append - add a single element at the end of a list
- Insert - adds an element to a specific index.
- Extend - Add multiple elements at the end of a list.
>>> my_list = [1,2,3,4,5]
>>> my_list.append(6)
>>> my_list => [1, 2, 3, 4, 5, 6]
List Operations
Insert
>>> my_list = [1,2,3,4,5]
>>> my_list.insert(1,0) #the first argument is the index and the second is an item
>>> my_list => [1,0,2,3,4,5]

Extend
>>> my_list = [1,2,3,4,5]
>>> my_list.extend([6,7,8])
>>> my_list => [1, 2, 3, 4, 5, 6, 7, 8]
List Operations
Removing an element:
- Pop - removes the last element if called with no argument or removes an
element at a specific index.
- Remove - called by passing an element as an argument and it removes the
first occurrence of the element.
- Clear - removes all elements from the list.
List Operations
>>> my_list = [1,2,3,4,5]
>>> my_list.pop()
>>> my_list => [1, 2, 3, 4]
>>> my_list.pop(0)
>>> my_list => [2,3,4]
>>> my_list.remove(2)
>>> my_list => [3,4]
>>> my_list.clear()
>>> my_list => []
List Operations
Concatenation and repetition:
- + - operator can be used to concatenate two lists
- * - operator can be used to repeat lists.
>>> [1,2,3] + [4,5,6] => [1,2,3,4,5,6]
>>> [1,2,3] * 2 => [1,2,3,1,2,3]
Traversing lists
i=0 my_list = [1,2,3,4,5]
my_list = [1,2,3,4,5] for i in my_list:
while(i < len(my_list)): print(i)
print(my_list[i])
i+=1
Nested List
We can create a list containing other lists.
>>> my_list = [[1,2,3],[3,4,5]]
>>> my_list[1] => [3, 4, 5]
>>> my_list[1][1] => 4
Dictionary
Dictionaries is a collection of key value pairs.

Dictionaries are lists but their indexes (keys) can be any immutable data type.

my_dict = {“name”: “Abebe”,


“Age” : 23,
“Occupation”: “Driver”
}
Accessing elements in a dictionary
>>> my_dict = dict(name="Abebe",Age=23,Occupation="Driver")
>>> my_dict # {'name': 'Abebe', 'Age': 23, 'Occupation': 'Driver'}
>>> my_dict[“Age”] # 23
>>> my_dict.get(“Occupation”) => Driver
Dictionary Operations
Accessing contents of a dictionary:
- Keys - returns an iterable object containing the list of keys in a
dictionary
- Values - returns an iterable object containing the list of values in a
dictionary
- Items - return an iterable object containing a list of tuple containing
key value pairs
Dictionary Operations
>>> my_dict = dict(name="Abebe",Age=23,Occupation="Driver")
>>> my_dict.keys() # dict_keys(['name', 'Age', 'Occupation'])
>>> my_dict.values() #dict_values(['Abebe', 23, 'Driver'])
>>> my_dict.items() #dict_items([('name', 'Abebe'), ('Age', 23), ('Occupation',
'Driver')])
Adding item to dictionaries
>>> my_dict = dict(name="Abebe",Age=23,Occupation="Driver")
>>> my_dict["height"] = 1.78
>>> my_dict["name"] = "Bekele" #modifing an item
>>> my_dict #{'name': 'Bekele', 'Age': 23, 'Occupation': 'Driver', 'height': 1.78}
Adding multiple items
>>> my_dict = dict(name="Abebe",Age=23,Occupation="Driver")
>>> new_data = dict(Weight = 80,Salary = 3000)
>>> my_dict.update(new_data)
>>> my_dict #{'name': 'Abebe', 'Age': 23, 'Occupation': 'Driver',
'Weight': 80, 'Salary': 3000}
Traversing through a dictionary
my_dict = dict(name="Abebe",Age=23,Occupation="Driver")
for i in my_dict:
#i iterates of the keys of the dictionary
print(my_dict[i])
‘in’ operator
The in operator in Python is used to check if an element exists
within an iterable, such as a list, tuple, string, set, or dictionary.

When used with dictionaries, it checks if a key is present in the


dictionary.
‘in’ operator
>>> my_list = [1,2,3,4,5]
>>> 3 in my_list #True
>>> my_dict = dict(name="Abebe",Age=23,Occupation="Driver")
>>> “Height” in my_dict #False
>>> greeting = “Hello”
>>> “o” in greeting #True
Dictionary Exercise
Copy a paragraph from a random wikipedia article and write a function
that returns a dictionary containing every unique word as a key and
their number of occurrences in the paragraph as a value.

Write a function that takes a dictionary and a value as an argument and


returns the key of the value if the value exists.
Tuples
Tuples are sequences of values and indexed by integer.

Tuples are immutable.

Can contain heterogeneous values.

>>> my_tuple = (1,2,3)


Indexing Tuples
Tuples are indexed by integers.
>>> my_tuple = (1,2,3,4)
>>> my_tuple[0] #1
>>> my_tuple[1] # 2
Tuples can also sliced with lists with starting index, end index, and step
>>> my_tuple[2:] # (3,4)
>>> my_tuple = tuple(range(1,10))
>>> my_tuple #(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> my_tuple[::2] #(1, 3, 5, 7, 9)
Tuple Operations
Same with list we can do concatenation and repetition.
- + - operator to concatenate tuples
- * - operator to repeat tuples

>>> my_tuple = (1,2,3)


>>> my_tuple + (4,5,6) #1, 2, 3, 4, 5, 6)
>>> my_tuple = (1,2,3)
>>> my_tuple * 2 #(1, 2, 3, 1, 2, 3)
Tuple Operations
- Count - Counts the number of occurrences of an element with in a
tuple
>>> my_tuple = (2,2,2,2)
>>> my_tuple.count(2) #4

=> Count function can also be used to count occurrences of an element


with in a list.

You might also like