0% found this document useful (0 votes)
5 views

Python_Module3_Notes_Lists

Module III of the Python Programming on Raspberry PI course focuses on lists, which are ordered sequences of values that can contain mixed data types. It covers list creation, mutability, indexing, slicing, and various built-in methods for manipulating lists, such as append, extend, sort, and remove. Additionally, it discusses list operations, traversing lists, and deleting elements using methods like pop and remove.
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)
5 views

Python_Module3_Notes_Lists

Module III of the Python Programming on Raspberry PI course focuses on lists, which are ordered sequences of values that can contain mixed data types. It covers list creation, mutability, indexing, slicing, and various built-in methods for manipulating lists, such as append, extend, sort, and remove. Additionally, it discusses list operations, traversing lists, and deleting elements using methods like pop and remove.
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/ 11

Python Programming on Raspberry PI (22ECE136) Module III

MODULE III
LISTS

Dept of ECE, BNMIT Page 1


Python Programming on Raspberry PI (22ECE136) Module III

LISTS
 A list is an ordered sequence of values.
 It is a data structure in Python. The values inside the lists can be of any type (like integer, float,
strings, lists, tuples, dictionaries etc) and are called as elements or items.
 The elements of lists are enclosed within square brackets.
 For example,
ls1=[10,-4, 25, 13]
ls2=[“Tiger”, “Lion”, “Cheetah”]
 Here, ls1 is a list containing four integers, and ls2 is a list containing three strings.
 A list need not contain data of same type.
 We can have mixed type of elements in list.
 For example,
ls3=[3.5, „Tiger‟, 10, [3,4]]
 Here, ls3 contains a float, a string, an integer and a list.
 This illustrates that a list can be nested as well.
 An empty list can be created any of the following ways –
>>> ls =[]
>>> type(ls)
<class 'list'>
or
>>> ls =list()
>>> type(ls)
<class 'list'>
 In fact, list() is the name of a method (special type of method called as constructor – which will be
discussed in Module 4) of the class list.
 Hence, a new list can be created using this function by passing arguments to it as shown below –

>>> ls2=list([3,4,1])
>>> print(ls2)
[3, 4, 1]

Lists are Mutable


 The elements in the list can be accessed using a numeric index within square-brackets.
 It is similar to extracting characters in a string.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[1])
hi
>>> print(ls[2])
[2, 3]
 Observe here that, the inner list is treated as a single element by outer list. If we would like to
access the elements within inner list, we need to use double-indexing as shown below –

>>> print(ls[2][0])
2

Dept of ECE, BNMIT Page 2


Python Programming on Raspberry PI (22ECE136) Module III
>>> print(ls[2][1])
3
 Note that, the indexing for inner-list again starts from 0.
 Thus, when we are using double- indexing, the first index indicates position of inner list inside
outer list, and the second index means the position particular value within inner list.
 Unlike strings, lists are mutable. That is, using indexing, we can modify any value within list.
 In the following example, the 3rd element (i.e. index is 2) is being modified –

>>> ls=[34, 'hi', [2,3],-5]


>>> ls[2]='Hello'
>>> print(ls)
[34, 'hi', 'Hello', -5]
 The list can be thought of as a relationship between indices and elements. This relationship is
called as a mapping. That is, each index maps to one of the elements in a list.
 The index for extracting list elements has following properties –

 Any integer expression can be an index.


>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[2*1])
[2,3]
 Attempt to access a non-existing index will throw and IndexError.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[4])
IndexError: list index out of range
 A negative indexing counts from backwards.
>>> ls=[34, 'hi', [2,3],-5]
>>> print(ls[-1])
-5
>>> print(ls[-3])
hi
 The in operator applied on lists will results in a Boolean value.
>>> ls=[34, 'hi', [2,3],-5]
>>> 34 in ls
True
>>> -2 in ls
False

 Traversing a List
 A list can be traversed using for loop.
 If we need to use each element in the list, we can use the for loop and in operator as below
>>> ls=[34, 'hi', [2,3],-5]
>>> for item in ls:
print(item)
34
hi
[2,3]
-5

Dept of ECE, BNMIT Page 3


Python Programming on Raspberry PI (22ECE136) Module III
 List elements can be accessed with the combination of range() and len() functions as well –

ls=[1,2,3,4]
for i in range(len(ls)):
ls[i]=ls[i]**2

print(ls)

#output is
[1, 4, 9, 16]
 Here, we wanted to do modification in the elements of list. Hence, referring indices is suitable
than referring elements directly.
 The len() returns total number of elements in the list (here it is 4).
 Then range() function makes the loop to range from 0 to 3 (i.e. 4-1).
 Then, for every index, we are updating the list elements (replacing original value by its square).

 List Operations
 Python allows to use operators + and * on lists.
 The operator + uses two list objects and returns concatenation of those two lists.
 Whereas * operator take one list object and one integer value, say n, and returns a list by repeating
itself for n times.

>>> ls1=[1,2,3]
>>> ls2=[5,6,7]
>>> print(ls1+ls2) #concatenation using +
[1, 2, 3, 5, 6, 7]

>>> ls1=[1,2,3]
>>> print(ls1*3) #repetition using *
[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>> [0]*4 #repetition using *


[0, 0, 0, 0]

 List Slices
 Similar to strings, the slicing can be applied on lists as well. Consider a list t given below, and a
series of examples following based on this object.
t=['a','b','c','d','e']

 Extracting full list without using any index, but only a slicing operator –
>>> print(t[:])
['a', 'b', 'c', 'd', 'e']
 Extracting elements from 2nd position –
>>> print(t[1:])
['b', 'c', 'd', 'e']

Dept of ECE, BNMIT Page 4


Python Programming on Raspberry PI (22ECE136) Module III
 Extracting first three elements –
>>> print(t[:3])
['a', 'b', 'c']

 Selecting some middle elements –


>>> print(t[2:4])
['c', 'd']

 Using negative indexing –


>>> print(t[:-2])
['a', 'b', 'c']
 Reversing a list using negative value for stride –
>>> print(t[::-1])
['e', 'd', 'c', 'b', 'a']

 Modifying (reassignment) only required set of values –


>>> t[1:3]=['p','q']
>>> print(t)
['a', 'p', 'q', 'd', 'e']

Thus, slicing can make many tasks simple.


 List Methods
There are several built-in methods in list class for various purposes. Here, we will discuss some of
them.

 append(): This method is used to add a new element at the end of a list.

>>> ls=[1,2,3]
>>> ls.append(„hi‟)
>>> ls.append(10)
>>> print(ls)
[1, 2, 3, „hi‟, 10]
 extend(): This method takes a list as an argument and all the elements in this list are added at the
end of invoking list.
>>> ls1=[1,2,3]
>>> ls2=[5,6]
>>> ls2.extend(ls1)
>>> print(ls2)
[5, 6, 1, 2, 3]

Now, in the above example, the list ls1 is unaltered.


 sort(): This method is used to sort the contents of the list. By default, the function will sort the
items in ascending order.

>>> ls=[3,10,5, 16,-2]

Dept of ECE, BNMIT Page 5


Python Programming on Raspberry PI (22ECE136) Module III
>>> ls.sort()
>>> print(ls)
[-2, 3, 5, 10, 16]

When we want a list to be sorted in descending order, we need to set the argument as shown

>>> ls.sort(reverse=True)
>>> print(ls)
[16, 10, 5, 3, -2]

 reverse(): This method can be used to reverse the given list.


>>> ls=[4,3,1,6]
>>> ls.reverse()
>>> print(ls)
[6, 1, 3, 4]

 count(): This method is used to count number of occurrences of a particular value within list.
>>> ls=[1,2,5,2,1,3,2,10]
>>> ls.count(2)
3 #the item 2 has appeared 3 tiles in ls

 clear(): This method removes all the elements in the list and makes the list empty.
>>> ls=[1,2,3]
>>> ls.clear()
>>> print(ls)
[]
 insert(): Used to insert a value before a specified index of the list.
>>> ls=[3,5,10]
>>> ls.insert(1,"hi")
>>> print(ls)
[3, 'hi', 5, 10]
 index(): This method is used to get the index position of a particular value in the list.
>>> ls=[4, 2, 10, 5, 3, 2, 6]
>>> ls.index(2)
1
Here, the number 2 is found at the index position 1. Note that, this function will give index of only the
first occurrence of a specified value. The same function can be used with two more arguments start and
end to specify a range within which the search should take place.
>>> ls=[15, 4, 2, 10, 5, 3, 2, 6]
>>> ls.index(2)
2
>>> ls.index(2,3,7) 6
If the value is not present in the list, it throws ValueError.
>>> ls=[15, 4, 2, 10, 5, 3, 2, 6]
>>> ls.index(53)
ValueError: 53 is not in list

Dept of ECE, BNMIT Page 6


Python Programming on Raspberry PI (22ECE136) Module III
Few important points about List Methods:
1. There is a difference between append() and extend() methods. The former adds the argument as it
is, whereas the latter enhances the existing list. To understand this, observe the following example

>>> ls1=[1,2,3]
>>> ls2=[5,6]
>>> ls2.append(ls1)
>>> print(ls2)
[5, 6, [1, 2, 3]]

Here, the argument ls1 for the append() function is treated as one item, and made as an inner list
to ls2. On the other hand, if we replace append() by extend() then the result would be –
>>> ls1=[1,2,3]
>>> ls2=[5,6]
>>> ls2.extend(ls1)
>>> print(ls2)
[5, 6, 1, 2, 3]
2. The sort() function can be applied only when the list contains elements of compatible types. But,
if a list is a mix non-compatible types like integers and string, the comparison cannot be done.
Hence, Python will throw TypeError.
For example,
>>> ls=[34, 'hi', -5]
>>> ls.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

Similarly, when a list contains integers and sub-list, it will be an error.

>>> ls=[34,[2,3],5]
>>> ls.sort()
TypeError: '<' not supported between instances of 'list' and 'int'
Integers and floats are compatible and relational operations can be performed on them. Hence, we can
sort a list containing such items.

>>> ls=[3, 4.5, 2]


>>> ls.sort()
>>> print(ls)
[2, 3, 4.5]
3. The sort() function uses one important argument keys. When a list is containing tuples, it will be
useful. We will discuss tuples later in this Module.

4. Most of the list methods like append(), extend(), sort(), reverse() etc. modify the list object
internally and return None.
>>> ls=[2,3]
>>> ls1=ls.append(5)
>>> print(ls)
[2,3,5]

Dept of ECE, BNMIT Page 7


Python Programming on Raspberry PI (22ECE136) Module III
>>> print(ls1)
None
 Deleting Elements
Elements can be deleted from a list in different ways. Python provides few built-in methods for
removing elements as given below –
 pop(): This method deletes the last element in the list, by default.
>>> ls=[3,6,-2,8,10]
>>> x=ls.pop() #10 is removed from list and stored in x
>>> print(ls)
[3, 6, -2, 8]
>>> print(x)
10
When an element at a particular index position has to be deleted, then we can give that position as
argument to pop() function.
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1) #item at index 1 is popped
>>> print(t)
['a', 'c']
>>> print(x)
b
 remove(): When we don‟t know the index, but know the value to be removed, then this function
can be used.
>>> ls=[5,8, -12,34,2]
>>> ls.remove(34)
>>> print(ls)
[5, 8, -12, 2]
Note that, this function will remove only the first occurrence of the specified value, but not
all occurrences.
>>> ls=[5,8, -12, 34, 2, 6, 34]
>>> ls.remove(34)
>>> print(ls)
[5, 8, -12, 2, 6, 34]
Unlike pop() function, the remove() function will not return the value that has been deleted.

 del: This is an operator to be used when more than one item to be deleted at a time. Here also, we
will not get the items deleted.
>>> ls=[3,6,-2,8,1]
>>> del ls[2] #item at index 2 is deleted
>>> print(ls)
[3, 6, 8, 1]
>>> ls=[3,6,-2,8,1]
>>> del ls[1:4] #deleting all elements from index 1 to 3
>>> print(ls)
[3, 1]

Dept of ECE, BNMIT Page 8


Python Programming on Raspberry PI -22ECE136 Module III

Example: Deleting all odd indexed elements of a list –


>>> t=[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
>>> del t[1::2]
>>> print(t)
['a', 'c', 'e']

 Lists and Functions


 The utility functions like max(), min(), sum(), len() etc. can be used on lists.
 Hence most of the operations will be easy without the usage of loops.

>>> ls=[3,12,5,26, 32,1,4]


>>> max(ls) # prints 32
>>> min(ls) # prints 1
>>> sum(ls) # prints 83
>>> len(ls) # prints 7
>>> avg=sum(ls)/len(ls)
>>> print(avg)
11.857142857142858
 When we need to read the data from the user and to compute sum and average of those numbers,we
can write the code as below –

ls= list() while

(True):
x= input('Enter a number: ')
if x== 'done':
break
x= float(x)
ls.append(x)
average = sum(ls) / len(ls)
print('Average:', average)
 In the above program, we initially create an empty list.
 Then, we are taking an infinite while- loop.
 As every input from the keyboard will be in the form of a string, we need to convert x into floattype
and then append it to a list.
 When the keyboard input is a string „done‟, then the loop is going to get terminated.
 After the loop, we will find the average of those numbers with the help of built-in functions sum()
and len().

 List Arguments
 When a list is passed to a function as an argument, then function receives reference to this list.
 Hence, if the list is modified within a function, the caller will get the modified version.
 Consider an example –
def del_front(t):

Dept of ECE, BNMIT Page 9


Python Programming on Raspberry PI -22ECE136 Module III

del t[0]

ls = ['a', 'b', 'c']


del_front(ls)
print(ls)

# output is
['b', 'c']
 Here, the argument ls and the parameter t both are aliases to same object.
 One should understand the operations that will modify the list and the operations that create a newlist.
 For example, the append() function modifies the list, whereas the + operator creates a new list.
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1) #output is [1 2 3]
>>> print(t2) #prints None

>>> t3 = t1 + [5]
>>> print(t3) #output is [1 2 3 5]
>>> t2 is t3 #output is False
 Here, after applying append() on t1 object, the t1 itself has been modified and t2 is not going toget
anything.
 But, when + operator is applied, t1 remains same but t3 will get the updated result.
 The programmer should understand such differences when he/she creates a function intending to
modify a list.
 For example, the following function has no effect on the original list –

def test(t):
t=t[1:]

ls=[1,2,3]
test(ls)
print(ls) #prints [1, 2, 3]
 One can write a return statement after slicing as below –def
test(t):
return t[1:]

ls=[1,2,3]
ls1=test(ls)
print(ls1) #prints [2, 3]
print(ls) #prints [1, 2, 3]

 In the above example also, the original list is not modified, because a return statement always creates a
new object and is assigned to LHS variable at the position of function call.


Dept of ECE, BNMIT Page 10
Python Programming on Raspberry PI -22ECE136 Module III

 Lists and Strings


 Though both lists and strings are sequences, they are not same.
 In fact, a list of characters is not same as string.
 To convert a string into a list, we use a method list() as below –
>>> s="hello"
>>> ls=list(s)
>>> print(ls)
['h', 'e', 'l', 'l', 'o']
 The method list() breaks a string into individual letters and constructs a list.
 If we want a list of words from a sentence, we can use the following code –

>>> s="Hello how are you?"


>>> ls=s.split()
>>> print(ls)
['Hello', 'how', 'are', 'you?']

 Note that, when no argument is provided, the split() function takes the delimiter as white space.
 If we need a specific delimiter for splitting the lines, we can use as shown in following example –

>>> dt="20/03/2018"
>>> ls=dt.split('/')
>>> print(ls)
['20', '03', '2018']
 There is a method join() which behaves opposite to split() function.
 It takes a list of strings as argument, and joins all the strings into a single string based on the
delimiter provided.
 For example –
>>> ls=["Hello", "how", "are", "you"]
>>> d=' '
>>> d.join(ls)
'Hello how are you'

 Here, we have taken delimiter d as white space. Apart from space, anything can be taken as
delimiter. When we don’t need any delimiter, use empty string as delimiter.


**** ****

Dept of ECE, BNMIT Page 11

You might also like