Saturday, December 28, 2019

Python list statements

If we want to represent a group of individual objects as a single entity where insertion order preserved and duplicates are allowed, then we should go for list.
Insertion order preserved 
Duplicate objects are allowed
Heterogeneous objects are allowed 
List is dynamic because based on our requirement we can increase the size and descrease the size.
In list the elements will be placed within square brackets and with comma separator.
We can differentiate duplicate elements by using index and we can preserve insertion order by using index.Hence index will play very important role.
Python supports both positive and negative indexes. +ve index means from left to right where as negative index means right to left

-6                                -5                              - 4                             -3                              -2                              -1
10
A
B
20
30
10

0                                  1                               2                                3                               4                                5

[10,”A”,”B”,20,30,10]

List objects are mutable. i.e we can change the content.

Creation of list objects:

We can create empty list objects as follows 

list[]
print(list)
print(type(list))

[]
<class ‘list’>

If we know elements already then we can create list as follows list = [10,20,30,40]

With dynamic input:

list=eval(input(“Enter List:”))
print(list)
print(type(list))

D:\Python_classes>py test.py
Enter List:[10,20,30,40]
[10,20,30,40]
<class ‘list’>

With list() function:

l=list(range(0,10,2))
print(l)
print(type(l))

D:\Python_classes>py test.py
[0,2,4,6,8]
<class ‘list’>

Eg:

s=“karth”
l=list(s)
print(l)

D:\Python_classes>py test.py
[‘k’,’a’,’r’,’t’,’h’]

With split() function:

s=“Learning Python is very very easy !!!”
l=s.split()
print(l)
print(type(l))

D:\Python_classes>py test.py
[‘Learning’, ‘Python’, ‘is’, ‘very’, ‘very’, ‘easy’, ‘!!!’]
<class ‘list’>

Note: sometimes we can take list inside another list, such type of lists are called nested lists

[10,20, [30, 40]]

Accessing elements of list:

We can access elements of the list either by using index or by using slice operator(:)

By using index:

List follows zero based index, ie index of first element is zero 
List supports both +ve and -ve indexes 
+ve index meant for left to right
-ve index meant for right to left 
list = [10,20,30,40]

-4                                -3                              -2                            -1
10
20
30
40
0                                  1                                2                               3

print(list[0]) —> 10
print(list[-1]) —> 40
print(list[10]) —> IndexError: list index out of range.

By using Slice operator 

Syntax: list2 = list1[start:stop:step]

Start: It indicates the index where slice has to Start  [ Default Value is 0 ]
Stop: It indicates the index where slice has to End [ Default value is max allowed index of List ie Length of the List ]
Step: increment value [ Default value is 1 ] 

n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])

Output:

D:\Python_classes>py test.py

[3,5,7]
[5,7,9]
[4,5,6,7]
[9,7,5]
[5,6,7,8,9,10]

List vs Mutability 

Once we creates a List Object, we can modify its content. Hence List objects are mutable.

n=[10,20,30,40]
print(n)
n[1]=777
print(n)

D:\Python_classes>py test.py
[10,20,30,40]
[10,777,30,40]

Traversing the elements of list:

The sequential access of each element in the list is called traversal 

By using while loop: 

n = [0,1,2,3,4,5,6,7,8,9,10]
i = 0 
while l < len(n):
print(n[i])
i=I+1

D:\Python_classes>py test.py

0
1
2
3
4
5
6
7
8
9
10

By using for Loop:

n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)

D:\Python_classes>py test.py

0
1
2
3
4
5
6
7
8
9
10

To display only even numbers 

n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if  n1%2==0:
print(n1)

D:\Python_classes?py test.py
0
2
4
6
8
10

To display elements by index wise:

l = [“A”,”B”,”C”]
x = len(l)
for i in range(x):
print(l[I],”is available at positive index: “,I, “and negative index: “,I-x)

D:\Python_classes>py test.py

A is available at positive index: 0 and at negative index: -3 
A is available at positive index: 1 and at negative index: -2
A is available at positive index: 2 and at negative index: -1

Important function of list:

To get information about List:

len() : returns the number of elements present in the list 

Eg: n = [10,20,30,40]

print(len(n)) —> 4

count() : it returns the number of occurrences of specified item in the list.

n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))

D:\Python_classes>py test.py

1
4
2
0

index(): returns the index of first occurrence of the specified item.

n=[1,2,2,2,2,3,3]

print(n.index(1)) —> 0
print(n.index(2)) —> 1
print(n.index(3)) —> 5
print(n.index(4)) —> ValueErrorL 4 is not in list 

Note: if the specified element not present in the list then we will get ValueError. Hence before index() method we have to check whether item present in the list or not using in operator.

print(4 in n) —> False 

Manipulating Elements of List:

append() Function:

We can use append() function to add item at the end of the list.

list=[]
list.append(“A”)
list.append(“B”)
list.append(“C”)
print(list)

D:\Python_classes>py test.py
[‘A’,’B’,’C’]

To add all elements to list upto 100 which are divisible by 10

list=[]
for I in range(101):
if I%10==0:
list.append(i)
print(list)

D:\Python_classes>py test.py
[0,10,20,30,40,50,60,70,80,90,100]

Insert() function 

To insert item at specified index position 

n=[1,2,3,4,5]
n.insert(1,888)
print(n)

D:\Python_classes>py test.py
[1,888,2,3,4,5]

n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)

D:\Python_classes>py test.py
[999,1,2,3,4,5,777]

Note: if the specified index is greater than max index then element will be inserted at last position. If the specified index is smaller than min index then element will be inserted at first position.

Differences between append() and insert() 


Append() 
Insert()
In list when we add any element it will come in last i.e it will be last element.
In list we can insert any element in particular index number 

Extend () function 

To add all items of one list to another list.

l1.extend(l2)

All items present in l2 will be added to l1 

order1=[“Chicken”,”Mutton”,”Fish”]
order2=[“RC”,”KF”,”FO”]
order1.extend(order2)
print(order1)

D:\Python_classes>py test.py
['Chicken','Mutton','Fish','RC','KF','FO’]

order = [“Chicken”,”Mutton”,”Fish”]
order.extend(“Mushroom”)
print(order)

D:\Python_classes>py test.py
['Chicken','Mutton','Fish’,’m’,’u’,’s’,’h’,’r’,’o’,’o’,’m’]

Remove() function 

We can use this function to remove specified item from the list. If the item present multiple times then only first occurrence will be removed.

n=[10,20,10,30]
n.remove(10)
print(n)

D:\Python_classes>py test.py
[20,10,30]

If the specified item not present in list then we will get ValueError

n=[10,20,10,30]
n.remove(40)
print(n)

ValueError: list.remove(x): x nit in list 

Note: Hence before using remove() method first we have to check specified element present in the list or not by using in operator.

pop() function:

It removes and returns the last element of the list 
This is only function which manipulates list and returns some element.

n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)

D:\Python_classes>py test.py
40
30
[10,20]

If the list is empty then pop() function IndexError

n = []
print(n.pop()) —> IndexError: pop from empty list 

Note: 

pop() is only function which manipulates the list and returns some value
In general we can use append() and pop() functions to implement stack datastructure by using list, which follows LIFO ( last in first out ) order.

In general we can use pop() function to remove  last element of the list. But we can use to remove elements based on index.

n.pop(index) —> to remove and return element present at specified index
n.pop()  —> to remove and return last element of the list 

n = [10,20,30,40,50,60]
print(n.pop()) —> 60 
print(n.pop(1)) —> 20 
print(n.pop(10)) —> IndexError: pop index out of range.

Difference b/w remove() and pop()


Remove() 
pop()
We can use to remove special element from the list 
We can use to remove last element from the list
It cannot return value 
It returned removed element
If special element not available then we get VALUE ERROR
If list is empty then we get error

Note: List objects ate dynamic i.e based on our requirement we can increase and decrease the size.

append(), insert(), extend(), —> for increasing the size/growable nature.
Remove(), pop() —> for decreeing the size/shrinking nature.

Ordering elements of list 

reverse(): we can use to reverse()  order of elements of list.

n=[10,20,30,40]
n.reverse()
print(n)

D:\Python_classes>py test.py
[40,30,20,10]

Sort():  in list by default insertion order is preserved, if want to sort the elements of list according to default natural sorting order then we should go for the sort() method.

For numbers —> Default natural sorting order is ascending order 
For Strings:  Default natural sorting order is alphabetical order 

n = [20,5,15,10,0]
n.sort()
print(n) —> [0,5,10,15,20]

s = [“Dog”,Banana”,”Cat”,”Apple”]
s.sort()
print(s) —> [‘Apple’,’Banana’,’Cat’,’Dog’]

Note: to use sort() function, compulsory list should contain only homogenous elements, otherwise we will get typeerror

n = [20,10,”A”,”B”]
n.sort()
print(n)

TypeError: ‘<‘ not supported b/w instances of ’str’ and ‘int’

Note: In python 2 if list contains both numbers and strings then sort(0 function first sort numbers  followed by strings

n=[20,”B”,10,”A”]
n.sort()
print(n) # [10,20,’A’,’B’]

But in python 3 it is invalid 

To sort in reverse of default natural sorting order:

We can sort according to reverse of default natural sorting order by using reverse=True argument.

n = [40,10,30,20]
n.sort()
print(n) —> [10,20,30,40]
n.sort(reverse = True)
print(n) —> [40,30,20,10]
n.sort(reverse = False)
print(n) —> [10,20,30,40]

Aliasing and cloning of list objects:

The process of giving another reference variable to the existing list is called aliasing.

10 
20
30
40
x  y 

x=[10,20,30,40]
y=x
print(id(x))
print(id(y))

The problem in this approach is by using one reference variable if we are changing content , then those changes will be reflected to the other reference variable.


10
20 ( crossed)
30
4
                                       177

x = [10,20,30,40]
y = x
Y[1] = 777

print(x)  —> [10,777,30,40]

To overcome this problem we should go for cloning.
The process of creating exactly duplicate independent object is called cloning.

We can implement cloning by using slice operator or by using copy() function.

By using slice operator 

x = [10,20,30,40]
y = x[:]
y[1] = 777
print(x) —> [10,20,30,40]
print(y) —> [10,777,30,40]


10
20
30
40
(x)


10
20 (crossed)
30
40
                                      777 

(y)

Difference b/w = Operator and copy() function 

= operator meant for aliasing 
copy() function meant for cloning

Using Mathematical operator for list objects 

[ we can use + and * operators for list objects ].

Concatenation operator (+):

We can use + to concatenate 2 lists into a single list.

a=[10,20,30]
b=[40,50,60]
c = a+b
print(c) —> [10,20,30,40,50,60]

Note: to use + operator compulsory both arguments should be list objects , otherwise we will get TypeError.

c = a+40 —> TypeError: can only concatenate list ( not “int”) to list.
c = a+[40] —> valid 

Repetition operator(*):

We can use repetition operator (*) to repeat elements of list specified number of times.

x = [10,20,30]
y = x*3
print(y) —> [10,20,30,10,20,30,10,20,30]

Comparing List objects 

We can use comparison operators for list objects.















No comments:

Post a Comment