Module 2
Lists, Dictionaries and structuring
Data
Objectives.
What is List data type .
How to access elements in list.
Negative indexing.
List are mutable.
Working with Lists.(Programming examples)
Augmented assignment operator.
Using for loop in lists.
In and not in operators.
Lists In Python
❑In Python, a list is a built-in data structure that allows you to store and
manipulate a collection of items.
❑Lists are ordered, mutable (modifiable), and can contain elements of
different data types.
❑The items in the list are separated with the comma (,) and enclosed with the
square brackets [].
Example: # Creating a list
my_list = [1, 2, 3, 4, 5]
❑ Example of a list with different data types:
my_list = [1, "hello", 3.14, True]
How to access elements in List:
❑ Here, we can access elements in a list using indexing. Python uses zero-
based indexing, which means the first element is at index 0. You can access
elements by specifying their index within square brackets.
❑ Here's an example : my_list = [1, "hello", 3.14, True]
# Accessing elements in a list
print(my_list[0]) # Output: 1
print(my_list[1]) # Output: "hello"
My_list 1 hello 3.14 True
Index 0 1 2 3
Negative indexing:
We can also use negative indexing to access elements from the end of the list.
index -1 refers to the last element, -2 refers to the second-to-last element, and so
on.
Example: : my_list = [1, "hello", 3.14, True]
# Negative indexing
print(my_list[-1]) # Output: True
-4 -3 -2 -1
My_list
Index
Lists are mutable:
which means you can modify them by assigning new values to specific indices.
Example: my_list = [1, "hello", 3.14, True]
# Modifying elements in a list
my_list[1] = "world"
print(my_list) # Output: [1, "world", 3.14, True]
Working with lists
1. Creating a List:
my_list = [] # an empty list
my_list = [1, 2, 3] # a list with integer elements
my_list = ['apple', 'banana'] # a list with string elements
my_list = [1, 'apple', True] # a list with mixed data types
2. Accessing Elements:
my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) # Output: 'apple'
print(my_list[1]) # Output: 'banana'
print(my_list[-1]) # Output: 'cherry' (negative index starts from the end)
3. Modifying Elements:
my_list = ['apple', 'banana', 'cherry']
my_list[0] = 'orange' # Modifying an element
print(my_list) # Output: ['orange', 'banana', 'cherry’]
4. Slicing a List:
my_list = ['apple', 'banana', 'cherry', 'date']
print(my_list[1:3]) # Output: ['banana', 'cherry']
print(my_list[:2]) # Output: ['apple', 'banana']
print(my_list[2:]) # Output: ['cherry', 'date']
[Link] Elements:
my_list = ['apple', 'banana']
my_list.append('cherry') # Adding a single element at the end
print(my_list) # Output: ['apple', 'banana', 'cherry']
my_list.extend(['date', 'elderberry']) # Adding multiple elements at the end
print(my_list) # Output: ['apple', 'banana', 'cherry', 'date', 'elderberry’]
[Link] Elements:
my_list = ['apple', 'banana', 'cherry']
my_list.remove('banana') # Removing a specific element
print(my_list) # Output: ['apple', 'cherry']
popped_element = my_list.pop() # Removing the last element and returning it
print(popped_element) # Output: 'cherry'
print(my_list) # Output: ['apple']
7. List Length:
my_list = ['apple', 'banana', 'cherry']
length = len(my_list)
print(length) # Output: 3
8. Checking for an Element:
my_list = ['apple', 'banana', 'cherry']
print('banana' in my_list) # Output: True
Augmented assignment operator
❑ An augmented assignment operator is a shorthand notation for performing an arithmetic or
bitwise operation and assignment in a single step.
❑ It combines the arithmetic or bitwise operator with the assignment operator to simplify
code and make it more concise.
1. Addition & Assignment (+=): x+=y is equivalent to x=x+y
PROGRAM:
# Addition
a = 23
b=3
a += b
print('Addition = %d' %(a))
[Link] & Assignment (-=): x-=y 3. Multiplication & Assignment (*=): x*=y is
is equivalent to x=x-y equivalent to x=x*y
PROGRAM: PROGRAM:
# Subtraction # Multiplication
a = 23 a = 23
b=3 b=3
a -= b a *= b
print('Subtraction = %d' %(a)) print('Multiplication = %d' %(a))
[Link] (or Modulo) & Assignment (%=): x%=y is
4. Division & Assignment (/=): x/=y is equivalent to
equivalent to x=x%y
x=x/y
PROGRAM:
PROGRAM:
# Remainder or Modulo
# Division
a = 23
a = 23
b=3
b=3
a %= b
a /= b
print('Remainder or Modulo = %d' %(a))
print('Division = %f' %(a))
7. Integer Division & Assignment (//=): x//=y is equivalent to
6. Power & Assignment (**=): x**=y is x=x//y
equivalent to x=x**y PROGRAM:
PROGRAM:
# Power # Integer Division
a = 23 a = 23
b=3 b=3
a **= b a //= b
print('Power = %d' %(a)) print('Integer Division = %d' %(a))
[Link] Shift Right & Assignment (>>=): [Link] AND & Assignment (&=): x&=y is equivalent to
x>>=y is equivalent to x=x>>y x=x&y
PROGRAM: PROGRAM:
# Bitwise Shift Right # Bitwise AND
a = 23 a = 23
b=3 b=3
a >>= b a &= b
print('Bitwise Shift Right = %d' %(a)) print('Bitwise AND = %d' %(a))
Working with Lists:
Now we, want to store the names of cats, at first what you do in a easy way is:
catName1 = 'Zophie'
catName2 = 'Pooka'
catName3 = 'Simon'
catName4 = ‘Mixy'
catName5 = 'Fat-tail'
catName6 = ‘Musky‘
Bad way to write the program if you have many cats, so what you can do is assign variables and list the
cats
But,
print('Enter the name of cat 1:') print('Enter the name of cat 5:') What if you
catName1 = input() catName5 = input() want more than
6 cat names
print('Enter the name of cat 2:') print('Enter the name of cat 6:')
catName2 = input() catName6 = input()
print('Enter the name of cat 3:') print('The cat names are:')
catName3 = input() print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' +
print('Enter the name of cat 4:') catName4 + ' ' + catName5 + ' ' + catName6)
catName4 = input()
Instead of using multiple, repetitive variables, you can use a single
variable that contains a list value Output:
catNames = [] Enter the name of cat 1 (Or enter nothing to stop.):
while True: Zophie
print('Enter the name of cat ' + str(len(catNames) + 1) + ' Enter the name of cat 2 (Or enter nothing to stop.):
(Or enter nothing to stop.):') Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
name = input() Simon
if name == '': Enter the name of cat 4 (Or enter nothing to stop.):
break Mixy
Enter the name of cat 5 (Or enter nothing to stop.):
catNames = catNames + [name] # list Fat-tail
concatenation Enter the name of cat 6 (Or enter nothing to stop.):
print('The cat names are:') Musky
for name in catNames: Enter the name of cat 7 (Or enter nothing to stop.):
print(' ' + name) The cat names are: Zophie Pooka Simon Lady
Mixy Fat-tail Musky
catNames: Zophie Pooka Simon Mixy Fat tail Musky
0 1 2 3 4 5
Using for Loops with Lists
1. A for loop repeats the code block once for each value in a list or list-like value.
Ex: for i in range(4):
print(i)
Output:
0
1
2
3
2. A common Python technique is to use range(len(Fruits)) with a for loop to iterate
over the indexes of a list.
0 1 2 3
>>>Fruits = [‘Apple’, ‘Banana', ‘cherry', ‘Date’] Apple Banana Cherry Date
>>>for i in range(len(Fruits)):
print('Index ' + str(i) + ' in Chart is: ‘ + Fruits[i])
The in and not in Operators :
In Python, the in and not in operators are used to test whether a value is present or not present, respectively,
within a sequence
The in operator:
❑ The in operator returns True if a value is found within a
sequence and False otherwise.
Ex: fruits = ['apple', 'banana', 'orange’]
print('banana' in fruits) # Output: True
print('grape' in fruits) # Output: False
The not in operator:
❑ The not in operator is the negation of the in operator.
❑ It returns True if a value is not found within a sequence and
False
Ex: fruits = ['apple', 'banana', 'orange’]
print('banana' not in fruits) # Output: False
print('grape' not in fruits) # Output: True
Exercise:
1. What is []?
2. How would you assign the value 'hello' as the third value in a list
stored in a variable named spam? (Assume spam contains [2, 4, 6,
8, 10].) For the following three questions, let’s say spam contains
the list ['a', 'b', 'c', 'd’].
3. What does spam[int('3' * 2) / 11] evaluate to? 4
4. What does spam[-1] evaluate to?
5. What does spam[:2] evaluate to?
Methods:
❑ A method is the same thing as a function, except it is “called on” a value. it means that the method is
invoked or executed in relation to a specific object or instance.
1. Finding a Value in a List with the index() Method:
To find the index of a specific value in a list, we can use the index() method in Python.
The index() method returns the index of the first occurrence of the value in the list
my_list = [10, 20, 30, 40, 50]
Ex:
value = 60
my_list = [10, 20, 30, 40, 50]
value = 30
if value in my_list:
index = my_list.index(value)
index = my_list.index(value)
print("Index:", index) #Output Index :2
print("Index:", index)
else:
print("Value not found in the list.")
2. Adding Values to Lists with the append() and insert() Methods:
Using the append() method:
The append() method adds an element to the end of the list.
Ex:
my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list) # Output: [1, 2, 3, 4, 5]
Using the insert() method:
The insert() method inserts an element at a specific index in the list. The first argument to insert() is the
index, and the second argument is the value you want to add.
Ex: my_list = [1, 2, 3, 4]
my_list = [1, 2, 3, 4] my_list.insert(-1, 99)
my_list.insert(2, 99) print(my_list) # Output: [1, 2, 3, 99, 4]
print(my_list) # Output: [1, 2, 99, 3, 4]
The sort() method sorts the list in-place, meaning it modifies the original list and does not return a new sorted list.
3. Removing Values from Lists with remove() Method:
The remove() method removes only the first occurrence of the value. If the value appears multiple times in
the list, only the first occurrence will be removed.
Ex:
numbers = [1, 2, 3, 4, 5, 3, 6]
[Link](3)
print(numbers) # Output: [1, 2, 4, 5, 3, 6]
NOTE: Attempting to delete a value that does not exist in the list will result in a ValueError
error.
4. Sorting the Values in a List with the sort() Method:
▪ To sort the values in a list using the sort() method
▪ The sort() method sorts the list in-place, it means modifies the original list and does not return a new sorted
list.
Ex:
numbers = [5, 2, 8, 1, 9]
[Link]()
print(numbers) # Output: [1, 2, 5, 8, 9]
If you want to sort the list in descending order, you can pass the reverse=True argument to the sort()
method:
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
Ex: >>> [Link]()
numbers = [5, 2, 8, 1, 9] >>> spam
[Link](reverse=True) ['ants', 'badgers', 'cats', 'dogs', 'elephants']
print(numbers) # Output: [9, 8, 5, 2, 1]
>>> [Link](reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
Example Program: Magic 8 Ball with a List:
import random
"Concentrate and ask again",
responses = [ "Don't count on it",
"It is certain", "Outlook not so good",
"Without a doubt", "My sources say no",
"You may rely on it", "Very doubtful",
"Yes definitely", "My reply is no"
"It is decidedly so", ]
"As I see it, yes", input("Tell the Magic 8 Ball your question: ")
"Most likely", answer = [Link](responses)
"Yes", print(f"The Magic 8 Ball says: {answer}")
"Outlook good",
"Signs point to yes",
"Reply hazy try again",
"Better not tell you now",
"Ask again later",
"Cannot predict now",
List-like Types: Strings and Tuples, References:
Strings and tuples are two list-like types in Python. While they share some similarities with lists, there
are also important differences.
1. Strings:
• Strings are sequences of characters and are immutable, meaning they cannot be changed once created.
• You can access individual characters in a string using indexing, similar to lists. For example: my_string[0]
will give you the first character of the string.
• String literals are enclosed in either single quotes ('...') or double quotes ("...").
• Strings can be concatenated using the + operator or repeated using the * operator.
• Common string methods can be used to manipulate and modify strings, such as upper(), lower(), split(),
replace(), etc.
Ex: my_string = "Hello, world!"
print(my_string[0]) # Output: 'H’
print(my_string.upper()) # Output: 'HELLO, WORLD!’
print(my_string.split(',')) # Output: ['Hello', ' world!’]
new_string = my_string.replace("Hello", "Hi")
print(new_string) # Output: 'Hi, world!'
2. Tuples:
• Tuples are ordered collections of items enclosed in parentheses ( ). The items can be of any data type and
can be accessed using indexing.
• Tuples are immutable, like strings. Once created, their elements cannot be modified.
• Tuples are often used to store related pieces of data together. For example, a tuple (x, y) can represent a
coordinate pair.
• Tuples are commonly used for functions that need to return multiple values. The function can return a
tuple, and the values can be unpacked(assign values to it) into separate variables.
• Tuples can be concatenated using the + operator, but you cannot change or add elements to an existing
tuple.
Ex: my_tuple = (1, 2, 3, 4)
print(my_tuple[2]) # Output: 3
x, y, z = my_tuple # Unpacking the tuple
print(y) # Output: 2
concatenated_tuple = my_tuple + (5, 6)
print(concatenated_tuple) # Output: (1, 2, 3, 4, 5, 6)
[Link]
We know that variables store strings and integer values.
Ex: int a=10;
When you assign a list to a variable, you are actually assigning a list reference to the variable.
“A reference is a value that points to some bit of data, and a list reference is a value that points to a list.”
Ex: a = [1, 2, 3]
b=a # Both 'a' and 'b' now refer to the same list object
[Link](4)
print(a) # Output: [1, 2, 3, 4]
Passing References :
References are particularly important for understanding how arguments get passed to functions. When a
function is called, the values of the arguments are copied to the parameter variables. For lists, this means a
copy of the reference is used for the parameter.
Ex: def modify_list(my_list):
my_list.append(4) # Modifying the list
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # Output: [1, 2, 3, 4]
The copy Module’s copy() and deepcopy() Functions:
Python provides a module named copy that provides both the copy() and deepcopy() functions.
import copy
[Link](x)
[Link](x)
copy() function:
• The copy() function creates a shallow copy of an object.
• it creates a new object, but the contents are references to the original object's elements.
Ex:
import copy In this example , we use the copy()
original_list = [1, 2, [3, 4]] function to create a shallow copy of the
copied_list = [Link](original_list) original_list. When we modify the nested
list within the copied_list, the change is
copied_list[2].append(5) reflected in the original_list as well
because they still share the same nested
print(original_list) # Output: [1, 2, [3, 4, 5]] list object.
print(copied_list) # Output: [1, 2, [3, 4, 5]]
deepcopy() function:
The deepcopy() function creates a deep copy of an object. It returns a new object that is a complete and
independent copy of the original object, including all nested objects. Any changes made to the copied object
or its nested objects will not affect the original object.
Ex:
import copy
In this example, the deepcopy() function is
original_list = [1, 2, [3, 4]] used to create a deep copy of the original_list.
deep_copied_list = [Link](original_list) When we modify the nested list within the
deep_copied_list, the change is not reflected in
deep_copied_list[2].append(5) the original_list because they are now separate
objects.
print(original_list) # Output: [1, 2, [3, 4]]
print(deep_copied_list) # Output: [1, 2, [3, 4, 5]]
NOTE: the copy() function creates a shallow copy where the internal references are shared, while the
deepcopy() function creates an independent copy that includes copies of all nested objects.
THANK YOU
“The best way to predict the future is to create it”
-Abraham Lincoln