0% found this document useful (0 votes)
28 views18 pages

List Data Type

List data

Uploaded by

mg0129718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views18 pages

List Data Type

List data

Uploaded by

mg0129718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

LIST DATA TYPE

The Python Lists are containers that are used to store a list values of any
type. List Data types in Python are mutable data type. It is a collections of
items and each item has its own index value, like String Data type. Index
of first item is 0 and the last item is n-1. Here n is number of items in a list.
Indexing of list is done in two directions: Forward direction which is known
as Positive Indexing and Backward direction is known as Negative
Indexing.

Indexing of list :

Positive Index
Value

Negative Index

Creating a List :

Lists are enclosed in square brackets [ ] and each item is separated by a


comma.
Initializing a list :
Passing value in a list while declaring list is initializing of a list.
e.g.
list1=[‘English', ‘Hindi', 1997, 2000]
list2=[11, 22, 33, 44, 55]
list3=["a", "b", "c", "d"]

Blank list creation


A list can be created without element:
List4=[ ]
Empty List creation:
A empty list is creates as:
List5 = list()

Page 1 of 18
LIST DATA TYPE
Nested List creation:
A list containing another list item within the defined list is called Nested list.
Example :
Nested List
L1 = [3, 4, [ 5, 7,], 9, 12]
eval() : The eval() function in a Python can be used to evaluate and return
the result of an expression given as string.
Example:
>>> eval(‘5’ + ‘8’)
The above statement will give a result as 13, even though ‘5’ and ‘8’ are used
as string.
The eval() function can be used both for input and output purpose. To use
eval() function as input statement following syntax can be used:
Syntax:
< Variable>= eval(input( “ Message ”))
Example:
var= eval(input(“ Enter value = ”))
print(var, type(var))

In above code :
 if the value is entered in int form then output will be int and its data
type will be also int.
 if the value is entered in float form then output will be float and its
data type will be also float.
 if the value is entered in list form then output will be list and its data
type will be also list.
 if the value is entered in tuple form then output will be tuple and its
data type will be also tuple.

Page 2 of 18
LIST DATA TYPE

Access Items from a List


List items can be accessed using its index position.
e.g.
list = [3,5,9]
print(list[0]) Output
print(list[1]) 3
print(list[2]) 5
print('Negative indexing ') 9
print(list[-1]) Negative indexing
print(list[-2]) 9
print(list[-3]) 5
3

Iterating /Traversing Through a List:


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

Output :

3
5
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:]) [I, A ]
print(list[:]) [ I,N,D,I A]

Output :
Page 3 of 18
LIST DATA TYPE
['I', 'N', 'D']
['I', 'A']
['I', 'N', 'D', 'I', 'A']

Updating / Manipulating 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.

e.g. list.extend ([3,4])

Page 4 of 18
LIST DATA TYPE
List Operations
The data type list allows manipulation of its contents through various operations as
shown below.

Concatenation:
Python allows us to join two or more lists using concatenation operator depicted by the
symbol ‘+’.
Add Two Lists
e.g.
list = [1,2]
list2 = [3,4]
list3 = list + list2
print(list3)

OUTPUT
[1,2,3,4]
e.g :
list1 = [1,3,5,7,9]
list2 = [2,4,6,8,10]
list3 = list1 + list2
print(list3)

output :
[1, 3, 5, 7, 9, 2-, 4, 6, 8, 10]

Repetition:
Python allows us to replicate a list using repetition operator depicted by symbol ‘*’.
e.g. :

list1 = ['Hello']
print (list1 * 4)

Output:

['Hello', 'Hello', 'Hello', 'Hello']

Page 5 of 18
LIST DATA TYPE
Membership :

Like strings, the membership operators in checks if the element is present in the list
and returns True, else returns False.

list1 = ['Red', 'Green', 'Blue']


print( 'Green' in list1)
print('Cyan' in list1)

Output :
True
False

The not in operator returns True if the element is not present in the list, else it returns
False.

list1 = ['Red', 'Green', 'Blue']


print('Cyan' not in list1)
print('Green' not in list1)

Output :

True
False

Slicing :

Like strings, the slicing operation can also be applied to lists.

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print ( list1[2:6] )

Output :
['Blue', 'Cyan', 'Magenta', 'Yellow']

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print ( list1[2:20]) #second index is out of range, list1 is truncated to the
end of the list
Output :
Page 6 of 18
LIST DATA TYPE
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print ( list1[7:2] ) #first index > second index

Output :
[ ] #results in an empty list

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print( list1[:5]) #first index missing, return sub list from index 0 to 4

Output :

['Red','Green','Blue','Cyan','Magenta']

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print ( list1[0:6:2] ) #slicing with a given step size

Output:

['Red','Blue','Magenta']

#negative indexes

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print ( list1[-6:-2]) #elements at index -6,-5,-4,-3 are sliced

Output :

['Green','Blue','Cyan','Magenta']

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print ( list1[::2]) #step size 2 on entire list, both first and last index missing

Output:

Page 7 of 18
LIST DATA TYPE
['Red','Blue','Magenta','Black']

#negative step size


#whole list in the reverse order

list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']


print (list1[::-1]) #negative step size, #whole list in the reverse order

Output:

['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']

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.
list1 = [1,2]
list2 = [3,4]
list3 = list1 + list2
print(list3)

OUTPUT
[1,2,3,4]

Page 8 of 18
LIST DATA TYPE
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])

e.g.
dellist [0:2] # delete first two items
dellist # delete entire list

Basic List Operations

Python Expression Results Description

len([4, 2, 3]) 3 Length


[4, 2, 3] + [1, 5, 6] [4, 2, 3, 1, 5, 6] Concatenation
[‘cs!'] * 4 ['cs!', 'cs!', 'cs!', 'cs!'] Repetition
3 in [4, 2, 3] True Membership
for x in [4,2,3] : 423 Iteration
print (x,end= ' ')

Page 9 of 18
LIST DATA TYPE
Important methods and functions of List :

Function Description

list.append() Add an Item at end of a list

list.extend() Add multiple Items at end of a list

list.insert() insert an Item at a defined index

list.remove() remove an Item from a list

dellist[index] Delete an Item from a list

list.clear() empty all the list

list.pop() Remove an Item at a defined index

list.index() Return index of first matched item

list.sort() Sort the items of a list in ascending or descending order

list.reverse() Reverse the items of a list

len(list) Return total length of the list.

max(list) Return item with maximum value in the list.

min(list) Return item with min value in the list.

list(seq) Converts a tuple, string, set, dictionary into list.

Count(element) Counts number of times an element/object in the list

Page 10 of 18
LIST DATA TYPE

Program to Search an element in a list

Some Programs on List [ * Linear Search ]

list_of_elements= [4, 2, 8, 9, 3, 7]
x = int(input("Enter number to search: "))
found = False
for iin range(len(list_of_elements)):
if(list_of_elements[i] == x):
found = True
print("%d found at %dthposition"%(x,i))
break
if(found == False):
print("%d is not in list"%x)

Sorting :

Sorting is a process of arranging items systematically, according to a


comparison operator applied on the elements.

Page 11 of 18
LIST DATA TYPE

There are various sorting algorithms.


Two of them are :

1. Bubble Sort
2. Insertion Sort

Bubble Sort:

It is one of the simplest sorting algorithms. The two adjacent elements of a


list are checked and swapped if they are in wrong order and this process is
repeated until the whole list elements are sorted. The steps of performing a
bubble sort are:
1. Compare the first and the second element of the list and swap them
if they are in wrong order.
2. Compare these condition and the third element of the list and swap
them if they are in wrong order.
3. Proceed till the last element of the list in a similar fashion.
4. Repeat all of the above steps until the list is sorted.

Bubble sort is a sorting process in which it compares two adjoining values and exchange
them if they are not in proper order. Here in single Pass/Iteration at a time n-1 exchange
occurs and the process is repeated until the whole sequence is sorted. To sort unsorted
value, Bubble sort requires maximum (n-1) pass to sort the element, but many times it
sorts the value before (n-1) pass.
Example:
12 26 7 80 38 56
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

This is unsorted data. Now sorting it through Bubble Sort :

Page 12 of 18
LIST DATA TYPE
Pass- 1 Action
12 26 7 80 38 56 No Exchange
12 26 7 80 38 56 Exchange
12 7 26 80 38 56 No Exchange
12 7 26 80 38 56 Exchange
12 7 26 38 80 56 Exchange
12 7 26 38 56 80 Final Value after Pass-1
Pass- 2 Action
12 7 26 38 56 80 Exchange
7 12 26 38 56 80 No Exchange
Now it has been found that the given sequence is now sorted. So no need to process
further. And here sorted elements has been found in Pass-2 only. This is final
sorted elements.

Write an Algorithm to Sort the Linear List by using Bubble sort method

Step 1 : [ Start]
Step 2 : [ Loop ]
For I = L to U
Step 3 : [ Loop]
For J=l to [ (U-1)-I ]
Step 4 : [Check Condition ]
If Ar[J]>Ar[J+1] then
Step 5 : [ Compute ]
Temp = Ar[J]
Step 6 : [ Compute ]
Ar[J]= Ar[J + 1]
Step 7 : [ Compute ]
Ar[J+1] = Temp
# End of If
# End of Inner Loop J
# End of Outer Loop I
Step 8 : [Stop]
End

Page 13 of 18
LIST DATA TYPE
Insertion Sort:

Insertion sort is a method of sorting the given sequence not by exchanging the
value, but it is used to sort the value by inserting the value at it’s appropriate
position. In this sorting method very first element of the list is treated as a
sorted element and then next time next value is compared with previous value
and according to it’s position it get inserted at appropriate position.
Example.

12 26 7 80 38 56
This is unsorted data. Now sorting it through Insertion sort, the very first
element is treated as sorted element. Hence in Pass-1 value will be as :

Page 14 of 18
LIST DATA TYPE

Pass- 1 Action
12 26 7 80 38 56 No Action, as first element is
treated as sorted element

Pass- 2 Action
12 26 As 26 is greater than 12
hence the no 26 will get
inserted after 12 .

Pass- 3 Action
7 12 26 As 7 is smaller than 12, it get inserted before 12

Pass- 4 Action
7 12 26 80 As 80 is greater no, hence it get inserted at 4th
position only.

Pass- 5 Action
7 12 26 38 80 As 80 is greater no, hence it
get inserted at 4th position
only.

Pass- 6 Action
7 12 26 38 56 80 Final value in 6th pass is
sorted

As in each pass only one insertion is occurring , so Insertion sort will take
Maximum ( N) pass to sort the elements.

Page 15 of 18
LIST DATA TYPE
Write an algorithm to sort the list by using Insertion Sort.

Step 1 : [ Start]

Step 2 : [ Loop ]
For I = L to U
Step 3 : [ Compute]
temp=lst[I]
Step 4 : [ Re – Initialize]
J=I-1
Step 5 : [ Loop]
while lst[J]> temp and J >=0 :
Step 6 : [Compute]
lst[J+1]= lst[J]
Step 7 : [ Re – Initialize]
J=I-1

# End of While loop


Step 8 : [ Compute]
lst[j+1]=temp

# End of For Loop


Step 9 : [Stop]
End

Page 16 of 18
LIST DATA TYPE

Write a program in Python to Sort a List by using Bubble Sort Method.


# Program to sort a list by using Bubble Sort

alst=[]

n=int(input(" Enter how many value you want in the list "))

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

p=eval(input(" Enter value = "))

alst.append(p)

print (" The List items are as .........\n")

print("\t",alst)

print(" Sorting the elements by using Bubble sort")

L=len(alst)

for i in range (1,L):

for j in range(0,L-1):

if(alst[j]>alst[j+1]):

alst[j],alst[j+1]= alst[j+1], alst[j]

print("\n After sorting the Elements are as .....\n")

print("\t",alst)

Page 17 of 18
LIST DATA TYPE
Write a Program in Python to sort a List by using Insertion Sort Method.

# Program to sort a list by using Insertion sort

alst=[]
n=int(input("\t Enter how many value you want in the list "))
for i in range(1,n+1):
p=eval(input("\t Enter value = "))
alst.append(p)
print (" \t The List items are as .........\n")
print("\t",alst)

print(" Sorting the elements by using Insertion sort")


L=len(alst)
for i in range (1,L):
temp=alst[i]
j=i-1
while alst[j]>temp and j >=0 :
alst[j+1]=alst[j]
j=j-1
alst[j+1]=temp
print("\n After sorting the Elements are as .....\n")
print("\t",alst)

Page 18 of 18

You might also like