Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Lists

Lists
• Sequence of values called lists or elements
• Elements can be of any type
Creating Lists using the constructor of the
list class
• Create an empty list
L1=list()
• Create a list with any 3 integer elements
L2=list([10,20,30])
• Create a list with 3 string elements
L3=list([“Apple”, ”Banana”, ”Grapes”])
• Create a list with range()
L2=list(range(0,6))
Creating Lists without using the constructor
of the list class
• Create a list with integer
L1=[10,20,30]
• Create a list with 3 string elements
L2=[“Apple”, ”Banana”, ”Grapes”]
Accessing the elements of a list
Syntax:
Variable_Name[index]
Example:
Input:
>>>L1=([10,20,30,40,50])
>>>L1
>>>L1[0]
Output:
[10,20,30,40,50]
10
Negative list indices
Example:
Input:
>>>L1=([10,20,30,40,50,60])
>>>L1[-1]
>>>L1[-6]
Output:
60
10
List slicing
Syntax:
Variable_Name[start:end] Output:
Example: ['abcd', 786, 2.23, 'john', 70.2]
abcd
Input:
[786, 2.23]
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] [2.23, 'john', 70.2]
tinylist = [123, 'john'] [123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
List slicing with step size
Syntax:
Variable_Name[start:end:stepsize]
Example:
Input:
list1 = [ ‘Hello',1, ‘Monkey',2,’Dog’,3,’Donkey’]
print (list[0:6:2])
Output:
[ ‘Hello', ‘Monkey', ’Dog’,]
Examples
>>>list1 = [ 1,2,3,4 ]
>>>list1[:2] # Access first 2 elements
[1,2]
>>>list1[::-1] # Prints list in reverse order
[4,3,2,1]
>>>list1[-1:0:-1] # start index with -1 and end index with 0
[4,3,2]
Inbuilt functions for lists
• Len() – Returns the number of elements in a list
• Max() – Returns the element with the greatest value
• Min() – Returns the element with the lowest value
• Sum() – Returns the sum of all the elements
• Random.shuffle() – Shuffles the elements randomly
Examples
>>>L1=[“Red”,”Orange”,”Green”]
>>>L1
[‘Red’, ’Orange’, ’Green’]
>>>len(L1)
3
>>>L2=[10,20,30,40,50]
>>>L2
[10,20,30,40,50]
>>>max(L2)
50
>>>min(L2)
10
>>>from random import randint
>>>print(randint(0,9),randint(0,9))

# Five Digit OTP Genration


>>>from random import randint
>>>for i in range(1,11):

>>>print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),sep
='')
Examples
>>> import random
>>> random.shuffle(l1)
>>> l1
[50, 30, 40, 20, 10]
>>> l1=[10,20,30,40,50]
>>> l1
[10, 20, 30, 40, 50]
>>> sum(l1)
150
What is the output of the program?

x=[10,20,30,40]
y=x
print(x)
print(y)
x[0]=70
print(x)
print(y)
y[1]=90
print(x)
[10, 20, 30, 40]
print(y)
[10, 20, 30, 40]
[70, 20, 30, 40]
[70, 20, 30, 40]
[70, 90, 30, 40]
[70, 90, 30, 40]
List Operator
1. + Operator:
3. in Operator:
>>> a = [1, 2, 3] >>> a = [1, 2]
>>> b = [4, 5, 6] >>> a
>>> c = a + b [1, 2]
>>> c >>> 4 in a
[1, 2, 3, 4, 5, 6] False
2. * Operator: >>> 1 in a
>>> a = [1, 2, 3] True
>>> b = 2 * a
>>> b
[1, 2, 3, 1, 2, 3]
List Operator
4. is Operator:
>>> a = ['A', 'B','C']
>>> b = ['A', 'B','C']
>>> a is b
False
>>> a = ‘Microsoft’
>>> b = ‘Microsoft’
>>> a is b
True
List Operator
5. del Operator:
L1=[10,20,30,40,50,60]
L1=[10,20,30,40,50,60] >>>del L1[2:5]
>>>del L1[2] >>>L1
>>>L1 [10, 20]
[10, 20, 40, 50, 60]
L1=[10,20,30,40,50,60]
L1=[10,20,30,40,50,60]
>>>del L1[:]
>>>L1
>>>del L1[-1]
[]
>>>L1
[10, 20, 30,40, 50]
x=[10,20,30,40]
x.append(50)
x.append(60)
print("x=",x)
List comprehensions
• Create a new list from existing sequences
• Requires lesser code and runs faster

Syntax
[<expression> for <element> in <sequence> if <conditional>]
List comprehensions
Create a list to store five different numbers such as 10,20,30,40 and 50.
Add number 5 to the existing elements of the list
Using List Comprehension Without Using List Comprehension
>>> l1=[10,20,30,40,50] >>> l1=[10,20,30,40,50]
>>> l1=[x+5 for x in l1] >>> l1
>>> l1 [10, 20, 30, 40, 50]
>>> for i in range(0,len(l1)):
[15, 25,35,45,55]
l1[i]=l1[i]+5
>>>l1
[15, 25,35,45,55]
Programs
Write a program to create a list with elements 1,2,3,4 and 5. Display
even elements of the list using list comprehension
L1=[1,2,3,4,5] Output:
print(“Content of list”) Content of list
print(L1) [1, 2, 3, 4, 5]
L1=[x for x in L1 if x%2==0] Even numbers from the
print(“Even numbers from the list”) list
[2, 4]
print(L1)
Programs
Write a program to create a list ‘A’ to generate squares of a number(from 1 to 10), list ‘B’ to
generate cubes of a number (from 1 to 10) and list ‘C’ with those elements that are even
and present in list ‘A’
print("List A=") Output:
A=[x**2 for x in range(11)] List A=
print(A) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
List B=
print("List B=")
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
B=[x**3 for x in range(11)]
Only even numbers from list A=
print(B) [0, 4, 16, 36, 64, 100]
print("Only even numbers from list A=")
C=[x for x in A if x%2==0]
print(C)
Programs
Consider a list with 5 different Celsius values. Convert all the values to
farenheit
print("Celsius=") Output:
cel=[10,20,31.3,40,39.2] Celsius=
[10, 20, 31.3, 40, 39.2]
print(cel) List B=
print("List B=") Farenheit=
print("Farenheit=") [50.0, 68.0, 88.34, 104.0, 102.56]

fah=[((float(9)/5)*x+32) for x in cel]


print(fah)
Programs
Consider a list with mixed type of elements, such as
L1=[1,’x’,4,5.6,’z’,9,’a’,0,4]. Create another list using list comprehension
which consists of only the integer element present within the list L1
print("List with mixed elements") Output:
L1=[1,'x',4,5.6,'z',9,'a',0,4] List with mixed elements
[1, 'x', 4, 5.6, 'z', 9, 'a', 0, 4]
print(L1) List with only integer elements
print("List with only integer elements") [1, 4, 9, 0, 4]
L2=[i for i in L1 if type(i)==int]
print(L2)
List Methods
Append: Adds an element to an end of the list
Example:
>>>L1=["Red","Orange","Green"]
>>>L1
['Red', 'Orange', 'Green']
>>> L1.append("Yellow")
>>>L1
['Red', 'Orange', 'Green', 'Yellow']
List Methods
Extend: Appends all the elements of the list
Example:
>>>L1=[1,2,3]
>>>L2=[4,5,6]
>>>L1
[1,2,3]
>>> L2
[4,5,6]
>>>L1.extend(L2)
L1
[1,2,3,4,5,6]
List Methods
Count: Returns the number of items from the list
Example:
>>>L1=["Red","Orange","Green","Red"]
>>>L1
['Red', 'Orange', 'Green', 'Red']
>>>L1.count("Red")
2
List Methods
Copy: Returns the copy of the list
Example:
>>>L1=["Red","Orange","Green"]
>>>L1
['Red', 'Orange', 'Green']
>>>L2=L1[:]
>>>L2
['Red', 'Orange', 'Green']
List Methods
index: Returns the index of first occurrence of the element
Example:
>>>L1=['A','B','C','B']
>>>L1
['A','B','C','B']
>>>L1.index('B')
>>>L1
1
List Methods
insert: Insert the element at a given index
Example:
>>>L1=['A','B',‘D',‘E']
>>>L1
['A','B',‘D',‘E']
>>>L1.insert(2,‘C')
>>>L1
['A','B',’C’,‘D',‘E']
List Methods
pop: Deletes the element at a given index
Example:
>>>L1=[10,20,30,40,50]
>>>L1.pop(2)
30
>>>L1
[10, 20, 40, 50]
>>>L1.pop() # removes last element
50
List Methods
remove: Removes the first occurrence of the element from the list
Example:
>>>L1=['A','B',‘D',‘E']
>>>L1
['A','B',‘D',‘E']
>>>L1.remove(‘B')
>>>L1
['A',‘D',‘E']
List Methods
reverse: Reverses all the elements from the list
Example:
>>>L1=['A','B',‘D',‘E']
>>>L1
['A','B',‘D',‘E']
>>>L1.reverse( )
>>>L1
[‘E‘, ‘D‘, ‘B’, 'A']
List Methods
sort: sort all the elements of the list
Example:
>>>L1=[‘E‘, ‘D‘, ‘B’, 'A']
>>>L1
[‘E‘, ‘D‘, ‘B’, 'A']
>>>L1.sort( )
>>>L1
['A','B',‘D',‘E']
With a given list L, write a program to print this list L after removing all
duplicate values with original order preserved.

Example:

If the input list is

12 24 35 24 88 120 155 88 120 155

Then the output should be

12 24 35 88 120 155
def remove(list1):
final_list = []
for num in list1:
if num not in final_list:
final_list.append(num) Input and Output:
return final_list
Input the list elements:
list1=[] 12 34 56 12 78 90 100 56 44
final=[]
print("Input the list elements:") New list without duplicates:
12 34 56 78 90 100 44
for x in input().split():
a=int(x)
list1.append(a)

final=remove(list1)
print("New list without duplicates:")
for i in range (0,len(final)):
What will be the output of following program
Input:
my_list=['two',5,['one',2]]
print(len(my_list))

Output:
3
What will be the output of following program
Input:
mixedlist=['pet','dog',5,'cat','good','dog']
mixedlist.count('dog')

Output:
2
What will be the output of following program
Input:
my_list=['Red',3]
my_list.extend("Green")
print(my_list)

Output:
['Red', 3, 'G', 'r', 'e', 'e', 'n']
What will be the output of following program
Input:
my_list=[1,'Red',2,'Green']
my_list.remove(2)
print(my_list)

Output:
[1, 'Red', 'Green']

You might also like