Saturday, November 21, 2020

List

 LIST


Introduction:

  • In Python, a list is a kind of container that contains collection of any kind of values.
  • A List is a mutable data type which means any value from the list can be changed. For changed values , Python does not create a new list. 
  • List is a sequence like a string and a tuple except that list is mutable whereas string and tuple are immutable. 
  • In this chapter we will see the manipulation on lists. We will see creation of list and various operation on lists via built in functions.
List Creation:
  • List is a standard data type of Python. It is a sequence which can store values of any kind.
  • Lists are enclosed in square brackets [ ] and each item is separated by a comma. 
For example  - 
[ ]                               Empty list 
[1, 2, 3]                      integers list 
[1, 2.5, 5.6, 9]             numbers list (integer and float) 
[ ‘a’, ‘b’, ‘c’]                 characters list 
[‘a’, 1, ‘b’, 3.5, ‘zero’]   mixed values list
[‘one’, ’two’, ’three’]     string list 

In Python, only list and dictionary are mutable data types, rest of all the data types are immutable data types.

List is a collections of items and each item has its own index value. Index of first item is 0 and the last item is n-1.Here n is number of items in a list.




List can be created as:
list1 = [‘English', ‘Hindi', 1997, 2000]; 
list2 = [11, 22, 33, 44, 55 ]; 
list3 = ["a", "b", "c", "d"];

List Manipulation

Access Items From A List List items can be accessed using its index position. e.g.
list =[3,5,9]    
print(list[0])      will give output as :  3
print(list[1])      will give output as :  5
print(list[2])      will give output as :  9
print('Negative indexing') will give output as : Negative indexing
print(list[-1])    will give output as : 9
print(list[-2])    will give output as : 5
print(list[-3])    will give output as : 3

Iterating Through A List 

List elements can be accessed using looping statement. 
e.g. 
list =[3,5,9] 
for i in range(0, len(list)): 
print(list[i]) 

Output :

9

Slicing of A List 

List elements can be accessed in subparts. 
e.g. 
list =['I','N','D','I','A']
print(list[0:3]) 
print(list[3:]) 
print(list[:]) 

Output 

['I', 'N', 'D'] 
['I', 'A'] 
['I', 'N', 'D', 'I', 'A'] 

Updating Lists 

We can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator. 
e.g. 

list = ['English', 'Hindi', 1997, 2000] 
print ("Value available at index 2 : ", list[2]) 
list[2:3] = 2001,2002                              #list[2]=2001 for single item update 
print ("New value available at index 2 : ", list[2]) 
print ("New value available at index 3 : ", list[3]) 

Output

('Value available at index 2 : ', 1997) 
('New value available at index 2 : ', 2001) 
('New value available at index 3 : ', 2002)

Add Item to A List 

append() method is used to add an Item to a List. 
e.g. list=[1,2] 
print('list before append', list) 
list.append(3) 
print('list after append', list) 

Output 

('list before append', [1, 2]) 
('list after append', [1, 2, 3]) 

NOTE :- extend() method can be used to add multiple item at a time in list.
eg - list.extend([3,4])


Add Two Lists 

e.g. 
list = [1,2] 
list2 = [3,4] 
list3 = list + list2 
print(list3) 

OUTPUT

 [1,2,3,4]

Delete Item From A List 

e.g. list=[1,2,3] 
print('list before delete', list) 
del list [1] 
print('list after delete', list) 

Output 

('list before delete', [1, 2, 3]) 

('list after delete', [1, 3]) 

Basic List Operations





Basic List Methods and Functions

Ex : L = [10,20,30,40,50,60,70,80,90,100]

Function/Method Name

Description

Example

len(list)

Returns number of elements in given list.

>>>len(l) 10

list(sequence)

It converts a sequence into list format.

>>>list(“python”) [‘p’,’y’,’t’,’h’,’o’,’n’]

List.index(<item>)

Returns the index of passed items.

>>> list1 = [10,20,30,20,40,10]

>>> list1.index(20) 1

>> list1.index(90) ValueError: 90 is not in list

List.append(<item>)

Appends a single element passed as an argument at the end of the list. The single element can also be a list

>>> list1 = [10,20,30,40]

>>> list1.append(50)

>>> list1

[10, 20, 30, 40, 50]

>>> list1 = [10,20,30,40]

>>> list1.append([50,60])

>>> list1

[10, 20, 30, 40, [50, 60]

List.extend(<list>)

Append the list (passed in the form of argument) at the end of list with which function is called.

>>> list1 = [10,20,30]

>>> list2 = [40,50]

>>> list1.extend(list2)

>>> list1

[10, 20, 30, 40, 50]

List.insert(<pos>,

<item>)

Insert the passed element at the passed position.

>>> list1 = [10,20,30,40,50]

>>> list1.insert(2,25)

>>> list1

[10, 20, 25, 30, 40, 50]

>>> list1.insert(0,5)

>>> list1

[5, 10, 20, 25, 30, 40, 50]

List.pop(<index>)

Delete and return the element of passed index. Index passing is optional, if not passed, element from last will be deleted.

>>> list1 = [10,20,30,40,50,60]

>>> list1.pop(3) 40

>>> list1

[10, 20, 30, 50, 60]

>>> list1 = [10,20,30,40,50,60]

>>> list1.pop() 60

List.remove(<value>)

It will delete the first occurrence of passed value but does not return the deleted value.

>>> list1 = [10,20,30,40,50,30]

>>> list1.remove(30)

>>> list1

[10, 20, 40, 50, 30]

>>> list1.remove(90) ValueError:list.remove(x):x

not in list

List.clear ( )

It will delete all values of list and gives an empty list.

>>> list1 = [10,20,30,40,50,30]

>>> list1.clear()

>>> list1 []

List.count (<item>)

It will count and return number of occurrences of the passed element.

>>> list1 = [10,20,30,10,40,10]

>>> list1.count(10) 3

>>> list1.count(90) 0

List.reverse ( )

It will reverse the list and it does not create a new list.

>>> list1 = [34,66,12,89,28,99]

>>> list1.reverse()

>>> list1

[ 99, 28, 89, 12, 66, 34]

List.sort ( )

It will sort the list in ascending order. To sort the list in descending order, we need to write----- list.sort(reverse

=True).

>>>list1 = ['Tiger','Zebra','Lion',

'Cat', 'Elephant' ,'Dog']

>>> list1.sort()

>>> list1

['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']

>>> list1 = [34,66,12,89,28,99]

>>> list1.sort(reverse = True)

>>> list1 [99,89,66,34,28,12]

List.sorted()

It takes a list as parameter and creates a

new list consisting of the same elements

arranged in sorted order

>>> list1 = [23,45,11,67,85,56]

>>> list2 = sorted(list1)

>>> list1

[23, 45, 11, 67, 85, 56]

>>> list2

[11, 23, 45, 56, 67, 85]

min()

 

max()

 

sum()

Returns minimum or smallest element of the list

 

Returns maximum or largest element of the list



 Returns sum of the elements of the list

>>> list1 = [34,12,63,39,92,44]


>>> min(list1) 12


>>> max(list1) 92


>>> sum(list1) 284



Nested Lists



When a list appears as an element of another list, it is called a nested list. Example :

>>> list1 = [1, 2, 'a', 'c', [6,7,8], 4, 9]

>>> list1[4] 


[6, 7, 8] 


To access the element of the nested list of list1, we have to specify two indices list1[i][j]. The first index I will take us to the desired nested list and second index j will take us to the desired element in that nested list.



Some Programs on List

 # find the max value in a list 

L=[]

n=int(input("Enter number of elements:"))

for i in range(1,n+1):

     b=int(input("Enter element:")) L.append(b)

     L.sort()

print("Largest element is:",L[n-1])




OUTPUT:

Enter number of elements: 4

Enter element: 10

Enter element: 5

Enter element: 8

Enter element: 9 

Largest element is: 10


# find the mean of a list

L=[]

n=int(input("Enter number of elements:")) 
for i in range(1,n+1):

 b=int(input("Enter element:")) L.append(b)

avg=sum(L)/n 
print("Average:",avg)



Run:

Enter number of elements: 4 Enter element: 10

Enter element: 5

Enter element: 7

Enter element: 2

Average: 6.0


* Frequency of an element in list

my_list= [101,101,101,101,201,201,201,201]

print("Original List : ", my_list( )

n=int(input("enter the element which you want to count:")) 
print( my_list.count(n))



Run:

Original List : [101, 101, 101, 101, 201, 201, 201, 201]
enter the element which you want to count: 201 
4

Exercise Questions:    List Manipulation

 

1 Mark Questions

Sr.

Question

Answer

1.

Suppose a list is L=[2, 33, "KVS", 14, 25], what is L[-3]?

“KVS”

2.

Find output: List1=[13,18,16,16,13,18]

print(List1.index(16))

2

3.

Given a list L=[1, 2, [“COMPUTER”, “SCIENCE”], “IS”, “TUPLE”]

What will be the value of L[- 3][1]

“SCIENCE”

4.

What is the output when we execute

list(“hello”)?

[‘h’,’e’,’l’,’l’,’o’]

2 Mark Questions

Sr.

Question

Answer

1.

Find the output of the following Python Code:

>>> L1=[10,20,30]

>>> L2=[110, 220, 330]

>>> L3=L1+L2

>>> L4=L3 [0:4]

>>> print (L4)

>>> L4[0]=L4[0]*10

>>> L4[2]=L4[1]*5

>>> L4[1]=L4[2]

>>> L4[3]=L4[3] - 10

>>> print (L4)

 

[10, 20, 30, 110]

 

[100, 100, 100, 100]

2.

How the pop( ) function is different from remove( ) function working with list in python ? Explain with example.

pop() function removes the last value and returns the same.

>>>l=[10,20,30,20]

>>>l.pop() 20

The remove() method removes the first matching value from the list.

>>>l.remove(20)

3.

Write a Python program to find and display those place names, in which there are more than 5 characters.

For example :

If the list l= ["Miao", "Tawang", "Chabua",

"Kimin", "Imphal", "Dimapur",”Goa”] The following should get displayed : Tawang

Chabua Imphal

Dimapur

l=["Miao", "Tawang", "Chabua",

"Kimin", "Imphal", "Dimapur","Goa"] for i in l:

if(len(i)>=5): print(i)

4.

What is the output when following code is executed ?

>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']

>>>print(names[-1][-1])

 

 

n

3 Mark Questions

Sr.

Question

Answer

1.

Write a program that will take a number from the key board and find its presence in the list [10,20,30, 40,50,60]. It will

print “Availabe” or “Not available”

List1=[10,20,30,40,50,60]

Num=int(input(“enter a number”))

if Num in List1:

print(“Available”)

else:

print(“Not Available”)

2.

What is the output when following code is executed ?

names1 = ['Amir', 'Bear', 'Charlton', 'Daman']

names2 = names1

names3 = names1[:] names2[0] = 'Alice' names3[1] = 'Ram' sum = 0

for ls in (names1, names2, names3): if ls[0] == 'Alice':

sum += 1

if ls[1] == 'Ram': sum += 10

print (sum)

12

3.

Write a program to check if a number is present in the list or not. If the number is present, print the position of the number. Print an appropriate message if the number is not present in the list.

lst = eval(input("Enter first list :-")) num = int(input("Enter the number which you want to search :-"))

if num in lst : print(lst.index( num ) )

else :

print("Number not found")

4.

Crate the following lists using a for loop:

 

(a).  A list consisting of the integers 0 through 49.

(b).  A list consisting the square of the integer 1 through 50

a)

lst = [ ]

for i in range(50): lst = lst + [ i ]

print(lst)

b) lst = [ ]

for i in range(51): lst = lst + [ i**2 ]

print(lst)

5.

Write a program to increment the elements of a list with a number.

lst = [ ] while True :

num = int(input("Enter a number :")) lst.append(num)

ch = input("for quit enter y or Y =") if ch == "Y" or ch=='y':

print(lst) break


4 Mark Questions

Sr.

Question

Answer

1.

Write a Python program to input 10 numbers to store in the list and print the third largest number.

For example, if the entered numbers in the list are List are

36, 25, 14, - 951, 75, - 85, 654, 88, 9521,

657, then output will be

The third largest number is : 654

L=list()

for i in range (10): 

 k=int(input("Enter a number :")) L.append(k)

  L.sort()

 print ("List is ", L)

 print ("The third largest number is

:",  L[-3])


2.

Create the following lists using a for loop:

(a)  A list containing of the integers 0 through 49.

 

(b)  A list containing squares of the integers 1 through 50.

(a) >>>L=list()

>>> for i in range (50):

L.append(i)

>>> print (L)

(b)   >>>L=list()

>>> for i in range (51):

L.append(i*i)

>>> print(L)

3.

Find the output of the following code:

 

 

>>> L=["These", "are", "a", ["few",

"words"], "that", "we", "will", "use"]

>>> print (L[3:4])

>>> print (L[3:4][0][1])

>>> print (L[3:4][0][1][2])

>>> print ("few" in L)

>>> print ("few" in L[3])

>>> print (L[0::2])

>>> print (L[4:])

>>> print (L)

 

 [['few', 'words']] words

r False True

['These', 'a', 'that', 'will']

['that', 'we', 'will', 'use']

['These', 'are', 'a', ['few', 'words'], 'that', 'we', 'will', 'use']

4.

Find and write the output of the following Python code :

x= [1, 2, [3, "KVS", 4], "KV"]

print(x[0])

print(x[2])

print(x[-1])

print(x[0:1]) print(2 in x) print(x[0]==8) print(len(x)) x.extend([12,32,4])

print(len(x))

1

[3, 'KVS',4]

 

KV

[1]

True

 

False

           4

7

5.

The record of a student (Name, Roll No., Marks in five subjects and percentage of marks) is stored in the following list:

sr = ['Raman','A-36',[56,98,99,72,69], 78.8]

Write Python statements to retrieve the following information from the list sr.

(a)    Percentage of the student

(b)    Marks in the fifth subject

(c)     Maximum marks of the student

(d)    Roll no. of the student

(e)    Change the name of the student from ‘Raman’ to ‘Raghav’

(a)>>>sr[3] or >>>sr[-1]

(b)>>>sr[2][4]

(c)>>>max(sr[2])

(d)>>>sr[1]

(e)>>>sr[0]=”Raghav”


******

1 comment: