Python_Module3_Notes_Lists
Python_Module3_Notes_Lists
MODULE III
LISTS
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]
>>> print(ls[2][0])
2
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
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]
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']
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]
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]
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
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'
>>> 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.
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]
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]
(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):
del t[0]
# 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
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.
**** ****