Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Programming 2

Lecture 2

Lists in Python

(Computer Programming 2)
Python Collections
 There are four collection data types in the Python programming
language:

 List is a collection which is ordered and changeable. Allows


duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows


duplicate members.

 Set is a collection which is unordered and unindexed. No


duplicate members.

 Dictionary is a collection which is unordered, changeable and


indexed. No duplicate members.

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

 When you need a non-homogeneous collection of elements.

 When you need the ability to order your elements.

 When you need the ability to modify or add to the collection.

 When you don't require elements to be indexed by a custom value.

 When you need a stack or a queue.

 When your elements are not necessarily unique.

(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, ...]

 This construct is known as a “list display”.

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

 Python also supports computed lists, called “list comprehensions”. In its


simplest form, a list comprehension has the following syntax:

L = [expression for variable in sequence]

 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.

 # mylist1 and mylist2 point to the same list


mylist1 = mylist2 = []

 # mylist3 and mylist4 point to the same list


mylist3 = []
mylist4 = mylist3

mylist5 = []; mylist6 = [] # different lists

(Computer Programming 2) 8
Accessing List Elements
 Individual elements in a list can be accessed using an index in square
brackets.

colors = ['red', 'blue', 'green']


print (colors[0]) # red
print (colors[2]) # green
print (len(colors)) # the length of list = 3

 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

print (colors[-1]) # green


print (colors[-2]) # blue
print (colors[-3]) # red

(Computer Programming 2) 9
Slicing and Sliding
 Slicing is an extended version of the indexing operator and can be used to
grab sublist

mylist[start:end] # items start to end-1


mylist[start:] # items start to end of the array
mylist[:end] # items from beginning to end-1
mylist[:] # a copy of the whole array

 You may also provide a step argument with any of the slicing constructions
above.

mylist[start:end:step] # start : end-1 : by step

(Computer Programming 2) 10
Slicing and Sliding cont’d

 The start or end arguments may be negative numbers, indicating a count


from the end of the array rather than the beginning. This applies to the
indexing operator.

mylist[-1] # last item in the array


mylist[-2:] # last two items in the array
mylist[:-2] # everything except the last two items

 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.

colors = ["red", "green", "blue", "purple"]


colors[2] = 'black'
print(colors)

Output
['red', 'green', 'black', 'purple']

 We can also change the value of an item by using a negative index


number instead:
colors[-3] = 'yellow' Output
print(colors)
['red', 'yellow', 'blue', 'purple']
(Computer Programming 2) 12
Looping Over Lists
 The for-in statement makes it easy to loop over the items in a list: red
green
colors = ["red", "green", "blue", "purple"] blue
for i in range(len(colors)): purple
print(colors[i])
output
 In the example above, first create a range corresponding to the indexes in the
list (0 to len(colors) - 1). Then loop over this range using “for-in loop”.

 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

print('c' not in my_list)


# Output: True

(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]]

 To access nested lists one needs additional square brackets []

print (list1[3][0]) # white


print (list1[4][1]) # 99
print (list1[0]) # 1
print (list1[3][1][0]) # b

(Computer Programming 2) 15
Nested Lists Cont’d

 Matrix Implementation: in the following example, a 3x4 matrix implemented


as a list of 3 lists of length 4:
1 4 5 12
-5 8 9 0
A = [[1, 4, 5, 12],
[-5, 8, 9, 0], -6 7 11 19
[-6, 7, 11, 19]] matrix
print("A[1] =", A[1]) # 2nd row
print("A[1][2] =", A[1][2]) # 3rd element of 2nd row
print("A[0][-1] =", A[0][-1]) # Last element of 1st Row

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]

 Assigning to an entire section (slice):

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

 When using assigning to an entire section (slice), the number of items


inserted doesn’t have to match the number of items deleted.

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.

a = [1, 99, 100]


a[2:3] = ['a','b','c','d']
# a = [1, 99, 'a', 'b', 'c', 'd']

(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.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: 123 Iteration
print (x)

(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

clear() Removes all the elements from the list

copy() Returns a copy of the list


count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list

(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].

fruits = ['apple', 'banana', 'cherry']


fruits.append("orange")
print(fruits)
Output: ['apple', 'banana', 'cherry', 'orange']
Add a list to a list:
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
print(a)

Output: ['apple', 'banana', 'cherry', ['Ford', 'BMW', 'Volvo']]

• Note: it modifies the original list


(Computer Programming 2) 22
Python List Methods Cont’d

 extend()
list.extend(iterable)
 Extend the list by appending all the items from the iterable.
 Equivalent to a[len(a):] = iterable.

Example: Add the elements of cars to the fruits list:

fruits = ['apple', 'banana', 'cherry']


cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)

Output: ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

• Can you use the + operator to add an item to list?

(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)

Example: Insert "orange" as the second item of the fruit list:


fruits = ['apple', 'banana', 'grape']
fruits.insert(1, "orange")
['apple', 'orange', 'banana', 'grape']

• How to insert an item into multidimensional list?


How can you insert the item 99 here

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[:].

fruits = ['apple', 'banana', 'orange']


fruits.clear()
print(fruits)

output: []

 copy()
The copy() function returns a list. It doesn't modify the original list.
. Equivalent to a[:]
Example: Copy the fruits list:

fruits = ['apple', 'banana', 'orange']


x = fruits.copy()
fruits.append("grape")
print(fruits) ['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'orange']
print(x)
output
(Computer Programming 2) 26
Python List Methods Cont’d

 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()

['orange', 'banana', 'apple']

(Computer Programming 2) 27
Python List Methods Cont’d

 count()
Example: Return the number of times the value “apple" appears in
the fruits list:

fruits = ['apple', 'banana', 'cherry' , 'apple']


x = fruits.count("apple")
# x = 2

count method with multidimensional

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.)

cars = ['Ford', 'BMW', 'Volvo']


cars.sort() # ['BMW', 'Ford', 'Volvo']

Sort the list descending:

cars = ['Ford', 'BMW', 'Volvo']


cars.sort(reverse=True) # ['Volvo', 'Ford', 'BMW']

(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.

No = [4, 55, 64, 32, 16, 32]


x = No.index(32)
# x = 3

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.

Example: Remove the "banana" element of the fruit list:

fruits = ['apple', 'banana', 'orange']


fruits.remove("banana") #['apple', 'orange']

(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.

5) Write a Python program to check whether a list contains a sublist.

6) Write a Python program to print average of list elements

7) Write a Python program to print even numbers and odd number separately
from a given list

(Computer Programming 2) 33

You might also like