Professional Documents
Culture Documents
Lecture_2 Lists-1_240108_050855
Lecture_2 Lists-1_240108_050855
Lecture 2
Lists in Python
(Computer Programming 2)
Python Collections
There are four collection data types in the Python programming
language:
Note: Python does not have built-in support for Arrays, but Python lists can be
used instead.
(Computer Programming 2) 2
Lists
The list is the most versatile datatype available in Python
The list type is a container that holds other objects/data types
Lists are ordered collections objects
They have no fixed size, It can be grown and shrunk.
They are mutable—unlike strings.
lists can be modified in place by assignment to offsets as well as a
variety of list method calls.
Each element or value that is inside of a list is called an item.
Example of Lists:
fruits = ['apple', 'orange', 'grape', 'banana']
even_no = [2,4,6,8]
list = ["orange", 1, True, 1.2, 'Car', None]
(Computer Programming 2) 3
When to Use Lists
(Computer Programming 2) 4
Creating Lists
To create a list in Python, we can use bracket notation to either create an
empty list or an initialized list.
mylist1 = [] # Creates an empty list
mylist2 = [expression1, expression2, ...]
Examples:
list1 = []
list2 = ['physics', 'chemistry', 1997, 2000]
list3 = [1, 2, 3, 4, 5 ]
list4 = ["a", "b", "c", "d"]
(Computer Programming 2) 5
Creating Lists Cont’d
Example:
no = [x for x in range(4)]
squared = [x**2 for x in range(4)]
print(no)
print(squared)
[0, 1, 2, 3]
[0, 1, 4, 9]
output
(Computer Programming 2) 6
Creating Lists Cont’d
We can also use the built-in list constructor to create a new list.
mylist1 = list()
mylist2 = list(sequence)
Examples:
list1 = list() # Create an empty list, list1=[]
list2 = list([22, 31, 61]) # elements 22, 31, 61
list3 = list(["C++", "Java", "C#"]) # Create a list
list4 = list("python")# Create a list with characters p, y, t, h, o, n
print(list1) []
print(list2) [22, 31, 61]
print(list3) ['C++', 'Java', 'C#']
print(list4) ['p', 'y', 't', 'h', 'o', 'n']
output
(Computer Programming 2) 7
Creating Lists Cont’d
Note that: Assignment with an = on lists does not make a copy. Instead,
assignment makes the two variables point to the one list in memory.
(Computer Programming 2) 8
Accessing List Elements
Individual elements in a list can be accessed using an index in square
brackets.
In addition to positive index numbers, we can also access items from the list
with a negative index number, by counting backwards from the end of the list,
starting at -1.
For the same list colors, the negative index breakdown looks like this
(Computer Programming 2) 9
Slicing and Sliding
Slicing is an extended version of the indexing operator and can be used to
grab sublist
You may also provide a step argument with any of the slicing constructions
above.
(Computer Programming 2) 10
Slicing and Sliding cont’d
Some examples:
mylist = [34, 56, 29, 73, 19, 62]
mylist[-2] # yields 19
mylist[-4::2] # yields [29, 19]
mylist[::2] # [34, 29, 19]
(Computer Programming 2) 11
Modifying Items in Lists
We can use indexing to change items within the list, by setting an index
number equal to a different value.
This gives us greater control over lists as we are able to modify and update
the items that they contain.
Output
['red', 'green', 'black', 'purple']
instead of retrieving the item indexes and looking up each element, we can
just loop over our list using a plain for-in loop.
red
for x in colors: green
print(x) blue
purple
output
(Computer Programming 2) 13
List Membership Test
An item in list can be tested if it exists in a list or not, using the keyword
“in”
Example:
my_list = ['p','r','o','b','l','e','m']
print('p' in my_list)
# Output: True
print('a' in my_list)
# Output: False
(Computer Programming 2) 14
Nested Lists
A nested list is a list that appears as an element in another list. With a nested
list a new dimension is created.
list1 = [1,2,[True,False],['white','black','green'],[1.2,99]]
list2 = [['ali',7303938],['ahmed',77345345]]
(Computer Programming 2) 15
Nested Lists Cont’d
A[1] = [-5, 8, 9, 0]
A[1][2] = 9
A[0][-1] = 12
output
(Computer Programming 2) 16
Changing Lists
When using a list, you can change its contents by assigning to either a
particular item (offset) or an entire section (slice).
they modify the subject list directly, rather than generating a new list object for
the result.
a = [1,2,3,4,5,6,7,8]
a[1] = 20
# a = [1,20,3,4,5,6,7,8]
a = [1,2,3,4,5,6,7,8]
a[1:3] = [99,100]
# a = [1,99,100,4,5,6,7,8]
(Computer Programming 2) 17
Changing Lists Cont’d
a = [1,2,3,4,5,6,7,8]
a[1:8] = [99,100]
# a = [1, 99, 100]
In the example above, the Python first deletes the one-item slice at [1:8]
(from offset 1, up to but not including offset 8), then inserts both 99 and
100 where the deleted slice used to be.
(Computer Programming 2) 18
Changing Lists Cont’d
More examples:
a = [1,2,3,4,5,6,7,8]
a[2:4] = ['a','b']
# a = [1, 2, 'a', 'b', 5, 6, 7, 8]
Replacement/insertion
a = [1,2,3,4,5,6,7,8]
a[1:1] = ['C++','JS']
# a = [1, 'C++', 'JS', 2, 3, 4, 5, 6, 7, 8]
Insertion (replace nothing)
a = [1,2,3,4,5,6,7,8]
a[1:7] = []
# a = [1, 8]
Deletion (insert nothing)
(Computer Programming 2) 19
Basic List Operations
Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too.
(Computer Programming 2) 20
Python List Methods
Python has some list methods that you can use to perform frequency
occurring task (related to list) with ease.
Method Description
append() Adds an element (string, number, object etc.) at the end of the list
extend() Add the elements of a list, to the end of the current list
index() Returns the index of the first element with the specified value
(Computer Programming 2) 21
Python List Methods Cont’d
append()
list.append(x) Add an item to the end of the list.
Equivalent to a[len(a):] = [x].
extend()
list.extend(iterable)
Extend the list by appending all the items from the iterable.
Equivalent to a[len(a):] = iterable.
(Computer Programming 2) 23
Python List Methods Cont’d
Extend vs Append
m = []
m.append('Car')
# ['Car']
m = []
m.extend('Car')
# ['C', 'a', 'r']
m.append(['Car'])
m.extend(['Car'])
- Output?
- Why?
(Computer Programming 2) 24
Python List Methods Cont’d
insert()
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the
element before which to insert, so a.insert(0, x) inserts at the front of the
list, and a.insert(len(a), x) is equivalent to a.append(x)
m = [[1,3,5],[3,4,1],[8,6,3],[9,2,3]]
(Computer Programming 2) 25
Python List Methods Cont’d
clear()
Removes all Items from the List (not deleting the List). Equivalent to del a[:].
output: []
copy()
The copy() function returns a list. It doesn't modify the original list.
. Equivalent to a[:]
Example: Copy the fruits list:
pop()
list.pop([i])
Remove the item at the given position in the list, and return it. If no
index is specified, a.pop() removes and returns the last item in the list.
Example: Remove the second element of the fruit list:
fruits = ['apple', 'banana', 'orange']
fruits.pop(1)
['apple', 'orange']
reverse()
Reverse the order of the fruit list::
fruits = ['apple', 'banana', 'orange']
fruits.reverse()
(Computer Programming 2) 27
Python List Methods Cont’d
count()
Example: Return the number of times the value “apple" appears in
the fruits list:
m = [[1,3,5],[3,4,1],[8,6,3],[9,2,3]]
x = m.count(1) # x = 0 (Why?)
x = m[0].count(1) # x = 1 (Why?)
(Computer Programming 2) 28
Python List Methods Cont’d
sort()
list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort
customization
• Example: sort the list alphabetically
(The sort() method sorts the list ascending by default.)
(Computer Programming 2) 29
Python List Methods Cont’d
index()
It returns the position at the first occurrence of the specified value. If not
found, it raises a ValueError exception indicating the element is not in the list.
x = No.index(99)
ValueError: 99 is not in list
(Computer Programming 2) 30
Python List Methods Cont’d
remove()
list.remove(x)
Remove the first item from the list whose value is x. It is an error if
there is no such item.
(Computer Programming 2) 31
List Built-in Functions
len() : It calculates the length of the list.
>>> x = [1,3,4,2]
>>> len(x)
max() : It returns the item from the list with the highest value.
>>> print(max(x))
>>> 4
min() : It returns the item from the Python list with the lowest value.
sum() : It returns the sum of all the elements in the list.
sorted() : It returns a sorted version of the list, but does not change the
original one.
>>> s = sorted(x)
>>> print(s)
>>> [1, 2, 3, 4]
(Computer Programming 2) 32
Exercises
1) Write a Python program to remove duplicates from a list of lists.
Sample list : [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
New List : [[10, 20], [30, 56, 25], [33], [40]]
2) Get first, second best scores from the list.
Ex: [86,86,85,85,85,83,23,45,84,1,2,0] => should get 86, 85
3) Write a Python program that takes two lists and returns True if they have at
least one common member.
4) Write a Python program to get the difference between the two lists.
7) Write a Python program to print even numbers and odd number separately
from a given list
(Computer Programming 2) 33