Python_Lists

 List Data Structure:

=================
Creation of list
-----------------------
1). l = [ ] -- Blank List

2). l = [10,20,30,40]

3).with dynamic list
-------------------------------
l = eval(input('Enter List:'))
print(type(l))

4).with list() function
--------------------------------
l = list(range(10))
print(l)

5).with split() function
----------------------------------
s = 'python is very easy'
l = s.split()
print(l)

Accessing elements of list:
----------------------------------------
1).By using index:
l = [10,20,30,40]
l[0] #10
l[-1] #40
l[10] #IndexError

2).By using slice operator:
n = [1,2,3,4,5,6,7,8,9,10]
n[2:7:2]#[3,5,7]
n[4::2]#[5,7,9]
n[3:7]#[4,5,6,7]
n[8:2:-2]#[9,7,5]
n[4:100]#[5,6,7,8,9,10]

List vs Mutability:
---------------------------
-->Once we create a list object, we can modify its content. Hence list objects are mutable.

Ex:
n = [10,20,30,40]
print(n)
n[1] = 333
print(n)#[10,333,30,40]

Traversing the elements of list:
-----------------------------------------------
The sequential access of each element in the list is called as traversal.

list_numbers = [0,1,2,3,4,5,6,7,8,9,10]
print(list_numbers)

a = 0
print(list_numbers[a]) # list_numbers[0]

a = a + 1
print(list_numbers[a]) # list_numbers[1]

a = a + 1
print(list_numbers[a]) # list_numbers[2]

a = a + 1
print(list_numbers[a]) # list_numbers[3]

a = a + 1
print(list_numbers[a]) # list_numbers[4]

a = a + 1
print(list_numbers[a]) # list_numbers[5]

print("Using Loop")

a = 0
number = len(list_numbers)
while ( a <= number):
print(list_numbers[a])
a = a + 1

#_______________________________________________________________________________________________________________________


1).By using while loop:
----------------------------------
l = [0,1,2,3,4,5,6,7,8,9,10]
i = 0
while i < len(l):
print(l[i])
i += 1

2).By using for loop:
------------------------------
l = [0,1,2,3,4,5,6,7,8,9,10]
for i in l:
print(i)

To display only even numbers
--------------------------------------------
for i in l:
if i%2 == 0:
print(i)

To display elements by index wiese:
------------------------------------------------------
-3 -2 -1
l = ['A','B','C']
0 1 2

l = ['A','B','C']
x = len(l)#3
for i in range(x):#0,1,2
print(l[i],'is available at +ve index:',i,'and at -ve index:',i-x)

Functions of list:
--------------------------
1.len():
Returns number of elements present in the list.

2.count():
It returns the number of occurences of specified item in the list.

3.index():
It returns index of first occurence of the specified element.

Q.
a = {1,1,1,2,2,6,6,6,6}
b = list(a)
print(b[2])#6



_________________________________________________________________________________________________________________________

Functions of list:
--------------------------
1.len():
Returns number of elements present in the list.

2.count():
It returns the number of occurences of specified item in the list.

3.index():
It returns index of first occurence of the specified element.

4.append():
To add item at the end of the list

l = [ ]
l.append(10)
l.append(20)
l.append(30)
print(l)

To add all elements to list upto 100 which are divisible by 10
--------------------------------------------------------------------------------------------
l = [ ]
for i in range(101):
if i%10 == 0:
l.append(i)
print(l)

5.insert():
To insert an item specified index position.

n = [1,2,3,4]
n.insert(1,333)
print('n:',n)#[1,333,2,3,4]

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.

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

Q.Difference between append() and insert()?
----------------------------------------------------------------
append():
In list when we add any element it will come in last. i.e it will be last element.

insert():
In list we can insert any element in a particular index number.

6.extend():
To add all items of one list to another list
l1.extend(l2)
All items present in l2 will be added to l1

Ex:
----
order1 = ['Chicken','Mutton','Fish']
order2 = ['KF','RC','BoomBoom']
order1.extend(order2)
print(order1)

Ex:
order1 = ['Chicken','Mutton','Fish']
order1.extend('Prawns')
print(order1)

7.remove():
To remove specified item from the list. If the item present multiple times then only first occurence will be removed.

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

-->If the specified element not present in the list we will get ValueError.

n = [10,20,30]
n.remove(50) #ValueError: list.remove(x): x not in list

8.pop():
It removes and returns the last element of the list.

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

-->If the list is empty then pop() function raises IndexError.
l = [ ]
l.pop()#IndexError: pop from empty list

Note:
--------
1.pop() is the only function which manipulates the list and returns some value.
2.In general we can use append() and pop() functions to implement stack datastructure by using list, which follows LIFO(Last In First Out) order.

-->We can use pop() function to remove elements based index also.

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]
print(n.pop())#40
print(n.pop(1))#20
print(n.pop(10))#IndexError

Q.Differences between remove() and pop()?
---------------------------------------------------------------
remove() pop()
------------- --------
1.To remove specified element from the list 1.To remove last element from the list

2.It cant return any value 2.It returned removed element.

3.If specified element not available then we 3.If list is empty then we will get an
will get ValueError. error IndexError.

Note:
List objects are dynamic i.e based on our requirement we can increase and decrease the size.
append(),insert(),extend()===>For increasing/growable nature
remove(),pop()===>For decreasing size/shrinking natrure

Ordering elements of the list:
---------------------------------------------
1.reverse():
-----------------
n = [10,30,20,40]
n.reverse()
print(n)#[40,20,30,10]

2.sort():
-----------
n = [10,30,20,40]
n.sort()
print(n)#[10,20,30,40]

n = ['sunny','chinny','bunny','vinny','pinny']
n.sort()
print(n)#['bunny', 'chinny', 'pinny', 'sunny', 'vinny']

n = [20,'B',10,'A',30,'C']
n.sort()#TypeError: '<' not supported between instances of 'str' and 'int'

Descending order:
---------------------------
n = [10,30,20,50,40]
n.sort()
print(n)
n.sort(reverse=True)
print(n)
n.sort(reverse=False)
print(n)

Aliasing and cloning of list objects:
-----------------------------------------------------
The process of giving another reference variable to the existing list is called as aliasing.

x = [10,20,30,40]
y = x #Aliasing
y[1] = 333
print('x:',x)#[10,333,30,40]
print('y:',y)#[10,333,30,40]

-->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.
-->To overcome this problem we should go for cloning.
-->The process of creating exactly duplicate independent object is called as cloning.
-->We can implement cloning by using slice operator or by using copy() function.

1).By using slice operator: 2).By using copy() function:
--------------------------------------- -----------------------------------------
x = [10,20,30,40] x = [10,20,30,40]
y = x[:] y = x.copy()
y[1] = 333 y[1] = 999
print('x:',x) print('x:',x)
print('y:',y) print('y:',y)

Q.Difference between = operator and copy() function?
--------------------------------------------------------------------------------
= operator meant for aliasing
copy() means cloning

Q.Difference between shallow cloning and deep cloning?



Mathematical operations for list objects:
-------------------------------------------------------------
1).Concatenation operator(+):
-------------------------------------------
a = [10,20,30]
b = [40,50,60]
c = a + b
print('c:',c)#[10, 20, 30, 40, 50, 60]

Ex:
a = [10,20,30]
b = [40,50,60]
c = a.extend(b)
print('a:',a)#[10, 20, 30, 40, 50, 60]
print('b:',b)#[40,50,60]
print('c:',c)#None

Note:
To use + operator both args should be list objects, otherwise we willl get an error.

Ex:
a= [10,20,30]
c = a + 40 #Invalid
c = a + [40] #Valid

Repetition operator(*):
----------------------------------
x = [10,20,30]
y = x * 2
print('y:',y)#[10,20,30,10,20,30]

Comparing list objects:
-----------------------------------
x = [50,40,30]
y = [10,20,30,40,50,60]
print(x > y)#True
print(x < y)#False

Nested List:
------------------
Sometimes we can take one list inside another list. Such type of lists are called as nested list

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

Nested list as matrix:
--------------------------------
In python we can represent matrix by using nested list.

n = [[10,20,30],[40,50,60],[70,80,90]]
print(n)
print('Elements by row wise:')
for r in n:
print(r)
print('Elements by matrix style:')
for i in range(len(n)):#0,1,2
for j in range(len(n[i])):#0,1,2
print(n[i][j],end=' ')
print()

List Comprehensions
--------------------------------
It is very easy way to create list objects from any iterable objects based on some condition.
Syn:
l = [expression for item in sequence if condition]

Ex:Print first 10-numbers squares in list format
-----------------------------------------------------------------------
l = [ ]
for i in range(1,11):
l.append(i*i)
print(l)

By using comprehension
-------------------------------------
l = [i*i for i in range(1,11)]
print(l)
l = [2*i for i in range(1,11)]
print(l)

To print only even numbers:
------------------------------------------
l = [i*i for i in range(1,11) if i%2 ==0]
print(l)

Print starting letter of each word
-------------------------------------------------
words = ['Chiranjeevi','Nag','Venkatesh','Balaiah']
o/p:['C','N','V','B']

l = [x[0] for x in words]
print(l)

Ex:
----
word = 'the quick brown fox jumps over the lazy dog'
o/p:[['THE',3],['QUICK',5],['BROWN',5].............['DOG',3]]

words = word.split()
l = [[w.upper(),len(w)] for w in words]
print(l)

Ex:w.a.p to display unique vowels present in the given string
--------------------------------------------------------------------------------------------
i/p:'naresh it technologies'

word = input('Enter the word to search for vowels:')
vowels = ['a','e','i','o','u']
found = [ ]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)


Comments

Popular posts from this blog

Python_While_Loop

Python_Lists_Loops

clinical_app