[go: up one dir, main page]

0% found this document useful (0 votes)
9 views12 pages

PYTHON- LISTS

The document provides an overview of lists in Python, describing them as dynamic arrays that can grow or shrink and can contain elements of different types. It covers list operations such as accessing elements, mutability, concatenation, merging, and various methods for manipulating lists, including sorting and reversing. Additionally, it introduces basic data structures like stacks and queues, explaining their characteristics and operations.
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)
9 views12 pages

PYTHON- LISTS

The document provides an overview of lists in Python, describing them as dynamic arrays that can grow or shrink and can contain elements of different types. It covers list operations such as accessing elements, mutability, concatenation, merging, and various methods for manipulating lists, including sorting and reversing. Additionally, it introduces basic data structures like stacks and queues, explaining their characteristics and operations.
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/ 12

Ler US Python

What are Lists?


Container is an entity which contains multiple data items. It is also
compound data type.
known as acollection or a
types:
Python has following container data
Lists Tuples
Sets Dictionaries
execution oft the program. Hence it is
Alist can growor shrink during
of this nature of lists they
also known as a dynamic array. Because
length data.
are commonly used for handling variable
comma-separated elements within [).
Alist is defined by writing
num = [10, 25, 30, 40, 100]
names = ('Sanjay', 'Anil', 'Radha', 'Suparna']
usually they are a collection
List can contain dissimilar types, though
of similar types. For exámple:
animal = [Zebra', 155.55, 110]

can be repeated, i.e., a list may contain duplicate


Items in a list multiple
used to repeat an element
items. Like printing, * can be
feasible.
time. An empty list is also
261 # duplicates allowed
ages = [25, 26, 25, 27,
num = [10] * 5
#stores [10, 10, 10,10, 10]
Ist =[] #empty list, valid/
Accessing List Elements

Entire list can be printed by just using the name of the, list
'saw', 'elbAl
l= [(Able, 'was', '", 'ere', "",
print(|)
usins
elements in a list can be accessed index
Like strings, individual The
also known as sequence types.
indices. Hence, they are
value starts from 0.
print(animals[1), ages[3])
ike strings, lists can be sliced,

print(animals[1:3))
print(ages|3:))

Looping in Lists
If we wish to process each itenm in
the list, we should be able to
iteratethrough the list. This can be done usingawhile or for
loop.
animals = [(Zebra', "Tiger, 'Lion', Jackal',
# using while loop 'Kangaroo']
i=0
while i< len(animals):
print(animals[il])
it=1
#using more convenient for loop
for a in animals :
print(a)

While iterating through a list using afor loop, if we wish


to keep
track of index of the element that a is referring to,
we can do so
using the built-in enumerate( )function.
animals = ('Zebra', 'Tiger','Lion', 'Jackal', 'Kangaroo']
tor index, a in enumerate(animals) :
print(index, a)
Basic List Operations
Mutability - Unlike strings, lists are mutable (changeable). So, lists
can be updated as shown below:

animals =[Zebra', Tiger', "Lion', 'Jackal', 'Kangaroo']


dges = (25, 26, 25, 27, 26, 28, 25|
animals[2] ='Rhinoceros
ages[5] =31
aßesl2:5] =(24. 25,32) ! sets items 2 to 4with values 24, 25,32
ages[2:5] =|| #delete items 2 to 4
Iet Us Python
102

concatenated
(appended) at the en
Concatenation - One list can be
shown below:
of another as
16, 17]
Ist = [12, 15, 13,23, 22,
Ist = Ist + (33, 44, 55) 13, 23, 22, 16,17, 33, 44,55)
# prints [12, 15,
print(lst)
create a new Iist.
Merging -Two lists
can be merged to

S= [10, 20, 30]


t= (100, 200, 300]
Z=S + t 300]
30, 100, 200,
print(z) # prints [10, 20,
list using the
string/tuple/set can be converted into a
Conversion - A
list( ) conversion function.
,'c, 'a']
# converts the string to a list ['A', ', ,
|= list('Africa')
another, both refer to the
same
On assigning one list to
Aliasing - known
one changes the other. This assignment is often
list.Changing
as shallow copy or alíasing. /

Ist1 = (10, 20, 30, 40, 50] to same list as Istl


ist2 = Istl # doesn't copylist. Ist2 refers
print(!st l) il prints |10, 20, 30, 40, 50
print(st2) # prints [10, 20, 30, 40, 50]
Ist1{0] = 100
print(lst1[0], Ist2|0]) # prints 100100
of one list into another:
Cloning - This involves copying contents
though both contain same
After copying both refer to different lists,
another. This operation
values. Changing one list, doesn't change
often knownas deep copy.

50}
Istl = (10, 20, 30, 40,
i enptylist
isi? = Istl, i5t2 refer to difterent lists
ist2 = st2 + Iti
/
# prints (10, 20, 30, 40, 50}
print(Ist1)
pint(ist2)
#prints |10, 20, 30, 40, 50)
ist1<0)= 100
printlst2[Ol, Ist2j0) # prints 100, 10
chapter 8: Lists
103

Searching- An element can be searched in


a list using the in
membership operator as shown below:

Ist =['a, 'e',lst", 'o', 'u']


res =
'a'in # return True since 'a' is
Ist present in list
res =z' not in #return True since'z' is absent in list
ldentity - Whether the two variables are
referring to the same
can be checked using the is identity operator as shown below: list
Isti=(10, 20, 30, 40, 50]
Ist2 =(10, 20, 30, 40, 50]
Ist3 = lst1
print(Ist1 is Ist2) # prints False
print(lst1 is Ist3) #prints True
print(lst1 is not Ist2) # prints True

Note the difference for basic types like int or str:

num1 = 10
num2 = 10
s1 ='Hi
$2 = 'Hi'
print(num1 is num2) # printsTrue
print(sl is s2) # prints True

Comparison It is possible to compare contents of two lists.


Comparison is done item by item till there is a mismatch. In the
Tollowing code it would be decided that a is less than b when 3 and 5
are compared.
a={1, 2, 3, 4]
b= (1, 2,5]
print(a <b) # prints True

tmptiness -We can check if alist is empty using not operator.


Ist =|)
if not lst: #Ist returns False
print('Empty list'")
check the result.
Alternately, we can convert a list to a bool and
Let Us Python
104

Ist =|| # prints False


print(bool(lst))

considered to be False:
following values are
Also note that the
None
Number equivalent to
zero: 0, 0.0, Oj
list andtuple:', "",()0
Empty string,
Empty set and dictionary: {}
Lists
Using Built-in Functions on
Many built-in functions
can be used with lists.
items in the list
# return number of
len(lst) the list
return maximum element in
max(lst) # the list
return minimum element in
min(Ist) #
elements in the list
# return sum of all
sum(lst) any element of Ist is
True
# return True if
any(lst) Ist are True
#return True if all elements of
all(lst) slice or entire list
# deletes element or
del( ) list, lst renmains
unchanged
# return sorted
sorted(lst)
reversed(lst) # used for reversing Ist
sorted(0 and
last 3, other functions are self-explanatory.
Except the usage
discussed in section after next. del( ) function's
reversed() are
is shown below:

Ist = [10, 20, 30,40, 50] list


Ist = del(ist(3]) # delete 3rd item in the
list
del(lst[2:5]) # delete items 2 to4 from the
del(Ist[:1) # delete entire list
entire list
Ist = (] # another way to delete an

are referring to same Iist, then deleting one


If multiple variables
doesn't delete the others.

Ist1 = [10, 20, 30, 40, 50]


Ist3 = Ist2 = lst1 # all refer to same list list
original

#Istl refers to empty list; Ist2, Ist3 to


Istl =[]
print(lst2) # prints ([10, 20, 30, 40, 50]
print(ist3) # prints [10, 20, 30, 40, 50]
hapter 8: LiSts
105

If multiple variables are referring to same list and we wish to delete


we can do so as shown below:
all,

Ist2{:] = | ) # list is emptied by deleting


all items
p r i n t ( l s t 2 )
# prints U
print(lst3) # prints ()

L i s t M e t h o d s

Any list is an object of type list. Its methods can be accessed using
the syntax Ist.method( ). Usage of some of the commonly used
methods is shown bèlow:

st=[12, 15, 13, 23, 22, 16, 17] # create list


Ist.append(22) # add new itemat end
Ist.remove(13) # delete item 13 from list
Ist.remove(30)
# reports valueError as 30is absent in Ist
ist.pop() #removes last item in list
Ist.pop(3) # removes 3rd item in the list
Ist.insert(3, 21) #insert 21 at 3rd position
Ist.count(23) # return no. of times 23 appears in lst
jdx = Ist.index(22) # return index of item 22
idx = Ist.index(50) # reports valueError as 50 is absent in Ist

Sorting and Reversing


for sorting is shown
Usage of list methods for reversing a list and
below:

Ist = (10, 2, 0, 50, 4]


Ist.reverse()
print(Ist) # prints (4, 50, 0, 2,10]
Ist.sort( )
print(lst) # prints [0, 2, 4, 10, 50]
order
Ist.sort(reverse = True) #sort items in reverse
print(ist) #prints [50, 10, 4, 2, 0]
manipulate
andsort( )do not return alist. Both
NOtethat reverse( )
the list in place.
and for sorting is
functions for reversing a list
Vsage of built-in
shown below:
Let Us Python
106

(10, 2, 0, 50, 4] # prints (0, 2, 4, 10, 50]


Ist =
print(sorted(ist)

orint(sorted(lst reverse =True)) tt prints [50, 10, 4, 2, 0)


# prints [4, 50, 0, 2, 10]
riint(list(reeversed(lst)))

Sorted list and keeps the


that sorted(Ofunction returns a newW
function returns a
list unchanged. Also, reversed()
Note

original
converted into a list using
reverseiterator object which has to
list_
Iistl )toget a reversed list.
shown below:
peversal is also possible usinga slicing operation as
4)
Ist = [10, 2, 0, 50,
print(Ist[:-1]) # prints [4, 50, 0, 2, 10]

List V a r i e t i e s

It is possible to create a list of lists (nested lists).

a=[1, 3, 5, 7,9]
b= (2, 4, 6, 8, 10]
c= [a, b]
print(c[0)[O], c[1][2]) # Oth element of Oth list, 2nd ele. of 1st list

Alist may be embedded in another list.


x= [1, 2, 3, 4]
y= [10, 20, x, 30]
print(y) # outputs [10, 20, [1, 2, 3, 4), 30]
It is possible to unpack a string or list within a list using the
7
operator.

S= 'Hello'
I= [*s]
print() #outputs ['H", 'e', '",'", 'o']

x= (1, 2, 3, 4)
y= |10, 20, *x, 30)
print(y) # outputs [10, 20, 1, 2, 3, 4, 30]
chapter 8: Lists 107

Stack Data Structure


Adata structure refers to an arrangement of data in memory.
Popular data structures are stack, queue, tree, graph and map.

Stack is a last in first out (LIFO) list, 0.e., last element that is added to
thelistis the first element that is removed from it.

Adding an element to a stack is called push operation and removing


an element from it is caled pop operation. Both these operations
are carried out at the rear end of the list.
Push and pop operations can be carried out using the append() and
nopl) methods of list object. This is demonstrated in Program 8.3.
Oueue Data Structure
added
Queue is a first in first out (FIFO) list, i.e.. first element that is
tothe list is the first element that is removed from it.
structure.
Lists are not efficient for implementation of queue data
not efficient, since it
With lists removal of items from beginning is
position after deletion.
involves shifting of rest of the elements by 1
for fast additions and deletions, deque class of collections
Hence
module is preferred.
queue. Addition and deletion in a
Deque stands for double ended
deque can take place at both ends.
structure is
deque class to implement a queue data
Usage of
demonstrated in Program 8.4.

P</ PiogtOms

Problem 8.1
on a list of names.
Perform the following operations
'Alka'
-'Anil', Amol', 'Aditya', 'Avi,
-Createa list of 5 names
-Insert a name 'Anui' before 'Aditya'
Appenda nameZulu'
Delete 'Avi' from the list
Replace 'Anil' with 'AnilKumar'
1 0 8
Let Us Python
all| the names in the list
Sort
- reversed. sorted list
.Print

PrOgram

C r e a t e
a list of 5 names
#names = ['Anil', 'Amol', 'Aditya', 'Avi", 'Alka')
print(nanes)

acert aname Anuj' before 'Aditya'


names.insert(2.'Anuj')
p r i n t ( n a m e s )

#append a name Zulu


names.append('Zulu')

print(names)

#
delete 'Avi' from the list
names.remove('Avi')

print(names)

# replace 'Anil' with 'AnilKumar!


j=names. index('Anil')
names[i]='Anilkumar'
print(names)

# sort all the names in the list


names.Sort( )
print(names)

#print reversed Sorted list


names.reverse()
print(names)

Output
{'Anil, 'Amol','Aditya', 'Avi', 'Alka']
['Anil', 'Arnol, 'Anu', 'Aditya'. 'Avi', 'Alka)
|'Anil', 'Amnot, 'Anuj', 'Aditya', 'Av', "Alka', Zulu')
l'Anil, 'Arnol', 'Anuj,'Aditya', 'Alka', 'Zulu')
lAnilkumar, 'Amol', 'Anuj', 'Aditya', 'Alka', "Zulu']
I'Aditya', 'AIka', 'Amol!, 'Anilkurnar', 'Anuj', Zulu')
Chopter & Lists 109

'Anuj' 'AnilKumar", 'Amol', 'Alka','litya']

problem8.2

performt h e following operations on a list of numbers.


.create
a list of 5 odd numbers
.Create a list, of 5 even numbers

.Combine the two lists


-Add prime numbers 11, 17, 29 at the beginning of the combined list
-Report how many elements are present in the list
last 3 numbers in the list with
-Replace 100, 200, 300
Delete all the numbers in the list
-
the list
-pelete
Program

#createa list of 5 odd numbers


a=(1,3, 5, 7, 9]
print(a)

#create a list of 5 even numbers


b=(2, 4, 6, 8, 10)
print(b)
#combine the two lists

print(a)

#add prime numbers 11, 17, 29 at the beginning of the combined list
a=(11, 17, 29] + a
print(a)

"teport how many elements are present in the list


num =len(a)
print{num}
ieplace last 3Dumtbers inthe list with 100, 200, 300
um-3num) 00, 200, 300]|

tilete all the numbers in the ist


Let Us Python
1 1 0

print(a)

delete
the list
#
del a

Output

(1, 3,5, 7, 9]
10]
|2, 4, 6,8, 6, 8, 101
I1, 3, 5, 7, 9, 2, 4, 8, 10]
11. 17, 29, 1, 3, 5, 7, 9, 2, 4, 6,
13
200, 300]
[11, 17,29, 1, 3, 5, 7, 9, 2, 4, 100,

Problem 8.3
structure. Stack is a Last In
Write a program to implement a Stack data
at the
First Out (LIFO) Iist in which addition and deletion takes place
same end.

Program

# stack - LIFO list


s=) # empty stack
# push elements on stack
s.append(10)
S.append(20)
S.append(30)
S.append(40)
S.append(50)
print(s)

#pop elements from stack


print(s.pop( )
print(s.pop( ))
print(s.pop())
print(s)
haptere. 111

outpur
30, 40, S0)

20,

p r o b l e m8 . 4

to
p r o g r a m implementa Queue data structure. Queue is a
First
a
(FIFO) liist, in which addition takes
Write

Out place at the rear end of


F i r s t

deletion takes place at the front end of


n q u e U e
and

the queue.
the

Program

i n p o r tc o l l e c t i o n s

=collections.deque( )

gappend('Suhana')

qappend('Shabana')

q.append('Shakila')

qappend('Shakira')

qappend(Sameera)

print(q)

print(q.popleft( ))
print(q.popleft( ))
print(g.popleft( ))
print(a)

Output
'Sameera'])
'Shabana'.
'Shakila' 'Shakira',
Uequel['Suhana'.

Suhana
Shabana
Shakila
deque{['Shakira', 'Sameera'])

You might also like