Thursday , November 21 2024
Class XI & XII Computer Science: Python

List in Python: 11th Class Computer Science Chapter 07

Chapter Name: List in Python [Chapter 07]
Class: 11th
Subject: Computer Science

7.1 Introduction: List in Python

  • List is a collection of elements which is ordered and changeable (mutable).
  • Allows duplicate values.
  • A list contains items separated by commas and enclosed within square brackets ([ ]).
  • All items belonging to a list can be of different data type.
  • The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list.

Difference between list and string:

7.2 Creating a list: List in Python

To create a list enclose the elements of the list within square brackets and separate the
elements by commas.

Syntax:
list-name= [item-1, item-2, …….., item-n]

Example:
mylist = [“apple”, “banana”, “cherry”] # a list with three items
L = [ ]                                                        # an empty list

7.2.1 Creating a list using list( ) Constructor:

It is also possible to use the list( ) constructor to make a list.

mylist = list((“apple”, “banana”, “cherry”)) #note the double round-brackets
print(mylist)
L=list( )                                                              # creating empty list

7.2.2 Nested Lists:

>> L=[23,’w’,78.2, [2,4,7],[8,16]] >>> L
[23, ‘w’, 78.2, [2, 4, 7], [8, 16]]

7.2.3 Creating a list by taking input from the user:

>> List=list(input(“enter the elements: “))
enter the elements: hello python

>> List
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

>> L1=list(input(“enter the elements: “))
enter the elements: 678546

>> L1
[‘6’, ‘7’, ‘8’, ‘5’, ‘4’, ‘6’] # it treats elements as the characters though we entered digits

Note: To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.

>> L1=eval(input(“enter the elements: “))
enter the elements: 654786

>> L1
654786 # it is an integer, not a list

>> L2=eval(input(“enter the elements: “))
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket

>> L2
[6, 7, 8, 5, 4, 3]

Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.

>> L1=eval(input(“enter the elements: “))
enter the elements: 7,65,89,6,3,4

>> L1
(7, 65, 89, 6, 3, 4) #tuple

7.3 Accessing lists: List in Python

  • The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
    indexes.
  • List-name[start:end] will give you elements between indices start to end-1.
  • The first item in the list has the index zero (0).

Example:
>>> number=[12,56,87,45,23,97,56,27]

 

>>> number[2] 87
>>> number[-1] 27
>>> number[-8] 12
>>> number[8]

IndexError: list index out of range

>>> number[5]=55 #Assigning a value at the specified index

>>> number
[12, 56, 87, 45, 23, 55, 56, 27]

7.4 Traversing a LIST:

Traversing means accessing and processing each element.

Method-1:

>>> day=list(input(“Enter elements :”))
Enter elements : sunday
>>> for d in day:
print(d)

Output:
s
u
n
d
a
y

Method-2:

>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])

Output:
w
e
d
n
e
s
d
a
y

7.5 List Operators:

  • Joining operator +
  • Repetition operator *
  • Slice operator [ : ]
  • Comparison Operator <, <=, >, >=, ==, !=

Joining Operator: It joins two or more lists.

Example:
>>> L1=['a',56,7.8] >>> L2=['b','&',6] >>> L3=[67,'f','p'] >>> L1+L2+L3
[‘a’, 56, 7.8, ‘b’, ‘&’, 6, 67, ‘f’, ‘p’]

Repetition Operator: It replicates a list specified number of times.
Example:
>>> L1*3
[‘a’, 56, 7.8, ‘a’, 56, 7.8, ‘a’, 56, 7.8] >>> 3*L1
[‘a’, 56, 7.8, ‘a’, 56, 7.8, ‘a’, 56, 7.8]

Slice Operator: 

List-name[start:end] will give you elements between indices start to end-1

>>> number=[12,56,87,45,23,97,56,27] >>> number[2:-2]
[87, 45, 23, 97] >>> number[4:20]
[23, 97, 56, 27] >>> number[-1:-6]
[ ] >>> number[-6:-1]
[87, 45, 23, 97, 56]

List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.

>>> number[1:6:2]
[56, 45, 97] >>> number[: : -1]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list

List modification using slice operator:

>>> number=[12,56,87,45,23,97,56,27] >>> number[2:4]=["hello","python"] >>> number

[12, 56, ‘hello’, ‘python’, 23, 97, 56, 27]

>>> number[2:4]=["computer"] >>> number
[12, 56, ‘computer’, 23, 97, 56, 27]

Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27] >>> number=[12,56,87,45,23,97,56,27] >>> number[2:3]=78 # 78 is a number, not a sequence
TypeError: can only assign an iterable

Comparison Operators:

  • Compares two lists
  • Python internally compares individual elements of lists in lexicographical
    order.
  • It compares the each corresponding element must compare equal and two
    sequences must be of the same type.
  • For non-equal comparison as soon as it gets a result in terms of True/False,
    from corresponding elements’ comparison. If Corresponding elements are
    equal, it goes to the next element and so on, until it finds elements that differ.

Example:
>>>L1, L2 = [7, 6, 9], [7, 6, 9] >>>L3 = [7, [6, 9] ]

For Equal Comparison:

For Non-equal comparison:

List Methods:

Deleting the elements from the list using del statement:

Syntax:
del list-name[index] # to remove element at specified index
del list-name[start:end] # to remove elements in list slice

Example:
>>> L=[10,20,30,40,50] >>> del L[2] # delete the element at the index 2
>>> L

[10, 20, 40, 50] >>> L= [10,20,30,40,50] >>> del L[1:3] # deletes elements of list from index 1 to 2.
>>> L

[10, 40, 50] >>> del L # deletes all elements and the list object too.
>>> L

NameError: name ‘L’ is not defined

Difference between del, remove( ), pop( ), clear( ):

Difference between append( ), extend( ) and insert( ) :

Programs related to lists in python:

Program-1 Write a program to find the minimum and maximum number in a list.

L=eval(input("Enter the elements: "))
n=len(L)
min=L[0] max=L[0] for i in range(n):
if min>L[i]:
min=L[i] if max<L[i]:
max=L[i] print("The minimum number in the list is : ", min)
print("The maximum number in the list is : ", max)

Program-2 Find the second largest number in a list.

L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0] for i in range(n):
if max<L[i]>second:
max=L[i] seond=max
print("The second largest number in the list is : ", second)

Program-3: Program to search an element in a list. (Linear Search).

L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4

Check Also

Class XI & XII Computer Science: Python

Tuple in Python: 11th Class Computer Science Chapter 08

Chapter Name: Tuple in Python [Chapter 08] Class: 11th Subject: Computer Science 8.1 INTRODUCTION: Tuple …