Python (Chapter 5.2) : Operations "ON" LIST
For any type of consultation, query or doubt. You may contact to the following: (+91) 9804 436 193 debabrataguha20@gmail.com
and join the group https://www.facebook.com/groups/331231161093613/
Part 1: Python Operations oN List
1. Declaring
a list named marks as following:
marks=[60,70,90,80]
“Operations OF
List” means the methods that will come under the LIST. We generally call them by
the following manner.
LISTname.METHODname()
as an example,
marks.reverse()
marks.copy()
etc.
These methods are generally
valid for list items. Surely these will not be applicable for all python items.
2. But
now we will learn how the common methods of python works ON a list.
Common Python
methods can be applied ON list. The way is like below
METHODname(LISTname)
as an example,
print ( students )
3. All
of the below functions can be applied ON
List.
sum() Returns the
sum of all the numbers in the list
max() Returns the
maximum element of given list
min() Returns the minimum element of given list
len() Returns the length of the list
4. To
physically reverse a list, we have already used list.reverse() function.
Now to see the elements
in a reversed order of a list, we can use
reversed(lst)
It is not reversing the list physically. Just returning the list in a reversed order. Actual List is still in the older format.
To see the reverse of a part of list we can use
reversed(lst[1:3])
5. To
physically sort a list, we have already used list.sort() function.
Now to see the
elements in a reversed order of a list, we can use
sorted(lst)
It is not sorting
the list physically. Just returning the list in a sorted order. Actual List is still
in the older format.
6. Use
of all() :
This method returns
TRUE if all the elements of that list are holding TRUE values
I know it is confusing
you. Let me share the examples when it will return FALSE. It will happen only
when there will be some FALSE or 0 (zero) values.
# “all values true”, that is why returns TRUE
l = [1, 3, 4, 5]
print(all(l))
# all values false,means “all values are not true”
that's why
# returns FALSE
l = [0, False]
print(all(l))
# one false value , “all values are not true”
that is why
# returns FALSE
l = [1, 3, 4, 0]
print(all(l))
# one true value, But “all values are not true”,
that is why
# returns FALSE
l = [0, False, 5]
print(all(l))
# empty iterable, No false value, means “all
values are true”, that is #why returns TRUE
l = []
print(all(l))
Even we can use this ALL function to check something for all the elements.
lst=[10,20,30,40,50]
print ( all ( x > 5 for x in lst))
# returns TRUE
or,
lst=[10,20,30,40,50]
print ( all ( x % 4 == 0 for x in lst))
# returns FALSE
7. Use
of any () :
This method returns
TRUE if any single element of that list is holding TRUE value
Means you have to
check “any value true?”
# “any value true”, answer is yes.. So
returns TRUE.
l = [1, 3, 4, 5]
print(any(l))
# “any value true”, answer is no.. So returns
FALSE.
l = [0, False]
print(any(l))
# “any value true”, answer is yes.. So
returns TRUE.
l = [1, 3, 4, 0]
print(any(l))
# “any value true”, answer is yes.. So
returns TRUE.
l = [0, False, 5]
print(any(l))
# “any value true”, answer is no.. So returns
FALSE.
l = []
print(any(l))
lst=[10,20,30,40,50]
print ( any ( x > 60 for x in lst))
# returns FALSE
or,
lst=[10,20,30,40,50]
print ( all ( x % 4 == 0 for x in lst))
# returns TRUE
Part 2: LIST COMPREHENSION:
List Comprehension is an elegant way of defining and creating a list. List Comprehension allows us to create a list using for loop with lesser code. What normally takes 3-4 lines of code, can be compressed into just a single line.
Normal coding:# initializing the list
list = []
for i in range(11):
if i % 2 == 0:
list.append(i)
# print elements
print(list)
Comprehension:
list = [i for i in range(11) if i % 2 == 0]
print(list)
Example of how to use Comprehension in better way:
1. We know how to print all the elements of a list. By print statement , elements will be printed as a list, means all the elements between the brackets. Try the below code.
numbers= [10,20,30,40,50]
# to print all the elements
as list
print (numbers)
output:
[10,20,30,40,50]2. To access all the elements of a list, call them out by their position
numbers= [10,20,30,40,50]
#to print all the elements
by calling their positions
for i in range (0,
len(numbers)):
print (numbers[i])
output:
10
20
30
40
50
3. To access all the elements of a list, call them individually sequentially . Do not need to think about their positions at all
numbers= [10,20,30,40,50]
#to print all the elements
individually by calling them directly
for i in numbers:
output:
1020
30
40
50
4. We can put the above-mentioned property while coping all the elements into another list. Though we can do the same using copy function as well.
numbers= [10,20,30,40,50]
numbers2= [ num for num in numbers]
print (numbers2)
output:
[10,20,30,40,50]
You can see we are
directly using the new format of FOR loop inside a list to fetch all the
elements.
5. We can still use this new FOR format to fetch elements after FILTERING. Filtering on the basis of some condition. Condition means IF statement.
numbers= [10,20,30,40,50]
numbers2= [ num for num in
numbers if num % 4 == 0]
print (numbers2)
output:
[20,40]
6. We can also use this new FOR format to fetch elements after FILTERING. Filtering on the basis of some condition on the place of list.
numbers= [10,20,30,40,50]
numbers2= [ numbers[num]
for num in range ( 0, len(numbers)) if num % 4 == 0]
print (numbers2)
output:
[10,50]
Here place 0 and place 4 is only divisible by 4. So printing the elements from those places.
7. We can also put composite IF statements here.
numbers= [10,20,30,40,50]
numbers2= [num for num in
numbers if num % 4 == 0 or num % 3 ==0]
print (numbers2)
output:
[20,30,40]
8. We can also put IF in Range statements.
numbers= [10,20,30,40,50]
numbers2= [ num for num in numbers if num in
range (30,50)]
print (numbers2)
output:
[30,40]
50 will not be in
the list, simply because the range is not inclusive. Means 30 to 50 means ,
included 30 and lesser than 50. All the FOR loop in python runs with the same
logic.
9. This same type of FOR-IF combinations can be applied on String lists as well.
words= [
"Binary", "World", "Computer" ,
"Science" ]
words2= [
w for w in words if len(w) in range (3,7)]
print
(words2)
output:
[ ‘Binary‘ , ’World’ ]
10.We can now think of a new list which will take few words from the old list. The selected words must starts with any letter between A to D
words= [
"Binary", "World", "Computer" ,
"Science" ]
words2= [
w for w in words if ord(w[0]) in range (65,68)]
print
(words2)
output:
[ ‘Binary‘ , ’Computer’ ]
The use of “ord()” method is to fetch
the ascii code of a letter.
11. We can even so the same from a string value. But out final output should be a list
word = "Bi**na+@ry--,@11W+=443@or!l&&*d))"
word2= [ w for w in word if
ord(w) in range (65,90) or ord(w) in range(97,122)]
print (word2)
output:
[ ‘B', 'i', 'n', 'a', 'r', 'y', 'W', 'o', 'r', 'l', 'd']
12. We can first put all the capital letters , then the small letters. To do that we need to write the same logic for 2 separate list and then merger them into one list
word = "Bi**na+@ry--,@11W+=443@or!l&&*d))"
word2= (
[ w for w in word if ord(w) in range (65,90) ]
+
[ w for w in word if ord(w) in range(97,122)]
)
print (word2)
output:
[ ‘B', 'W', 'i', 'n', 'a', 'r', 'y', 'o', 'r', 'l', 'd']
13. We can use these short cuts of list and finally convert the list into a String.
word = "Bi**na+@ry--,@11W+=443@or!l&&*d))"
word2= [ w for w in word if
ord(w) in range (65,90) or ord(w) in range(97,122)]
strng = “”.join(word2)
print (strng)
output:
BinaryWorld
14. Multidimension Comprehension:
a = 3
lst = [ ‘X’ for col in range (a) ]
print (lst)
output:
[ ‘X’ , ‘X’ , ‘X’ ]
a = 3
b = 4
lst = [ [‘X’ for col in range (a)] for col in
range (b) ]
print (lst)
output:
[[‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’]
a = 3
b = 4
c = 2
lst = [ [ ['X' for col in
range (a)] for col in range (b) ] for col in range (c)]
print (lst)
output:
[
[[‘X’,‘X’,‘X’],
[‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’] ],
[[‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’], [‘X’,‘X’,‘X’]
]
]
Part 3: LIST GENERATOR EXPRESSIONS:
Generator Expressions are somewhat similar to list comprehensions, but the former doesn’t construct list object. Instead of creating a list and keeping the whole sequence in the memory, the generator generates the next element in demand.
When a normal function with a return statement is called, it terminates whenever it gets a return statement. But a function with a yield statement saves the state of the function and can be picked up from the same state, next time the function is called
Coding:
generator_expression = (i for i in range(11) if i % 2 == 0)
for i in generator_expression:
print(i, end=" ")
If we want to print the generator expression object ,it will give the following output:
print(generator_expression)
<generator object at 0x000001452B1EEC50>
Part 4: USE OF IN / NOT IN:
“in” operator
:- This operator is used to check if an element is present in the list
or not. Returns true if element is present in list else returns false.
“not in” operator
:- This operator is used to check if an element is not present in the
list or not. Returns true if element is not present in list else returns false.
# Python code To demonstrate the working Of
# "in"
And "not
in"
# initializing list
lis = [1, 4, 3, 2, 5]
# checking If 4 Is In list Using "in"
if 4 In
lis:
Print ("List is
having element with value 4")
else :
Print ("List is not having element with value 4")
# checking If 4 Is Not list Using "not in"
If 4 Not
In lis:
Print
("List is not having element with value
4")
Else :
Print ("List is having element with value 4")
Part 5: EASINESS of HANDLING list:
1. We can easily convert something into list.
What will happen if we want to store some results inside a list. Like I do not want to reverse the original list , but I want to store the reversed list into another list. Obviously we will proceed and write the code like below:
arr = [1, 3, 4, 5, 7]
r=reversed(arr)
print (r)
Output:
< list_reverseiterator object at 0x7f5a105a1ef0>
Because the object returned by the reversed() function can not be fitted into a list variable. Even if we declare r=[] at the starting. So we need to use a function like list() to convert the object into list object. So the correct code would be like below:
arr = [1, 3, 4, 5, 7]
r=list (reversed(arr))
print (r)
Output:
[7, 5, 4, 3, 1]
lst=[10,20,30,40,50]
lst=lst *
2
print (
lst )
output:
[10,20,30,40,50,10,20,30,40,50]
lst=[10,20,30,40,50]
lst=lst *
3
print (
lst )
output:
[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50]
3. We can easily compare lists.
lst1=[10,20,30,40,50]
lst2=[10,20,30,40,50]
lst3=[5,10,20,30,40,50,60,70]
if (
lst1==lst2):
print ( "matched" )
else:
print ( " not matched" )
if ( lst1==list(lst3[1:6])):
print ( "matched" )
else:
print ( " not matched" )
output:
matched
matched
4. We can easily take a sublist and assign it to another list.
lst1=[5,10,20,30,40,50,60,70]
lst2=lst1[2:5]
print (lst2)
output:
[ 20 , 30 , 40 ]
5. We can easily sum up 2 list and assign it to another list.
lst1=[10,20,30,40,50]
lst2=[100,200]
lst3=lst1+lst2
print (lst3)
output:
[ 10 , 20 , 30 , 40 , 50 ,
100 , 200 ]
Comments
Post a Comment