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

Basic List operations

What is the use of data structures ?What are different data structures
used in Python?
• Data structures are used for the efficient organization of data in
memory so that the data can be accessed efficiently.
• Different data structures are List, Tuple, Sets, Dictionary
• These are used to represent collection of data
1. List
What are lists? What are the properties?
• Lists are used to store a collection of data, in a particular order
• List is created/ defined as follows
L1= [ 23, 15, 34.88, “acv”, 34]
•  Here, L1 is a list consists of data items/ elements of different types
• 23,15 and 34 are integers, 34.88 is floating point, “acv” is string literal
• One important property of lists is that they are mutable . It means
that we can easily modify the contents in a list
• L1[2]= 10 will replace 34.88 by 10
What are list operations?
1. To access elements in a list, use indexing and subscripting
• L1=[2, 4, 13, 17.8, 99, -56]
• To access the item 17.8, use the position(index). Indexing starts from
0, so position of 17.8 is 3
>>>print( L1[3])
• Ans: 17.8
• A special type of indexing is negative indexing. It is used to access
elements from the end of list.
L1=[2, 4, 13, 17.8, 99, -56]

• L1[-1] indicates the last element -56


• L1[-2] indicates the second last element 99, so on….
2. slicing
• It allows the access of a portion of the list.

L1[0:3] returns elements 2,4 and 13. Here though last index value
is 3, the corresponding value is omitted from the result.

L1[2:5] = 13, 17.8, 99


L1[ 1: 5] = [ 4,13,17.8, 99]
• The 5th position value is excluded
• So, in slicing, initial index is inclusive, but last index is exclusive
• A special type of indexing is also shown below.
• You can omit the last index value , if you want to access till the last
element
 
• >>> L1[ 2: ] gives you 13, 17.8, 99, -56
• : ] indicates the default end
• >>>L1[ 4: ] gives [ 99, -56]
the result of slicing is another list
• Similarly, if you want to access elements from the beginning, you may
omit initial index
• L1[ : 5] gives [ 2, 4, 13, 17.8,99]
• The last index value ( position 5 value -56) gets excluded here also
3. List concatenation
• L1 = [ 3, 45, 17]
• L2=[ 14, 7, 87]
• Print(L1+L2) gives the combined list
[ 3,45,17,14,7,87]
• Thus, two lists can be concatenated using + operator
4. L2=[ 5]
L2*3  [5, 5, 5]
What are different list functions? Explain with examples

1)To add new elements into the list


syntax: L1. append ( item)
• L1= [ 2, 4, 6, 8]
• >>>L1. append(10) gives [ 2,4,6,8,10]
• Append() function will add an item at the end of the list
 
L1=[] will create an empty list.
L1.append(item)
2) How to insert an element at a position?
List. insert( position, item)
• L1. insert( 2,5)
• The item 5 gets inserted at position 2
L1= [ 2, 4, 6, 8]

• >>> print( L1) gives [ 2,4, 5, 6, 8]


3) L1.extend()
• Add the elements of a list(or any iterable) to the end of
the current list
• L1=[10,20,30]
• L1.extend([40,50,60]) gives [10,20,30.40,50,60]
4) To find the length, use len( list)
• L1=[10,20,30]
• print(len(L1)) gives 3
• 5) To find the position of an element , use index()
• fruits = ['apple', 'banana', 'cherry']
• x = fruits.index("cherry")
• print(x)  2
• that index() returns only the position of first occurrence, if an item
occurs multiple times
• 6) To remove an element from the list using position, use pop()
• fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
• Ans: [ ‘apple’,’cherry’]
• 7) To remove an element from the list using the value, use remove()
• fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
• Ans:?
8) Use count() to find the number of occurrences of an item
• fruits = ['apple', ‘cherry’, 'banana', 'cherry']
x = fruits.count("cherry")
• Ans: 2
• 9) Use reverse() to reverse the order of elements
• fruits = ['apple', 'banana', 'cherry']
• fruits.reverse()
• print(fruits)
10)Use sort() to sort elements in ascending order
• L1=[ 34, 56,12, 8, 99]
• Print( L1.sort())
• If you want the result in descending order,
• L1.sort( reverse=True)
• Print(L1)
• 11) How do you iterate through a list for element wise processing?
• We can use for loop for accessing each elemnt
• Eg: L1= [1,2,3,4,5]
• for i in range( 0,5):
• print(L1[i])
• Ans: 1,2,3,4,5
• L1= [1,2,3,4,5]
l= len(L1)
for i in range( 0,l):
print(L1[i])
e. Write a program to search for an element in a list.

• L1= [ 10,20, 30,40,50]


• Check whether 50 is present or not. ( Do not use in operaor)
flag=0, key=50
length= len(L1)
for i in range( 0, length+1):
if L1[i]==key:
flag=1
break
if flag==1:
print(“found”)
Else:
print(“not found”)
• We can use in operator as membership operator
• >>>L1=[2,56,34,17,89]
• >>>Print ( 56 in L1) gives True
List of Lists
• L1= [[1,2,3] , [ 4,5,6], [ ‘x’,’y,’z’]]
• Elements inside a list are another lists
• L1[0]  [1,2,3]
• L1[0][1]  [2]
List comprehension
• V=[ ‘bus’, ‘car’,train’, ‘bicycle’]
Create a new list containing only items with ‘b’

Newlist=[]
For element in V: - Take every element in list
if ‘b’ in element:  if b is present in it
newlist.append( element)  put that vehicle in newlist
comprehension

• Newlist= [ element for element in L1 if ‘b’ in element]


expression for item in iterable, if condition==True

Adv: Make code simpler


Lambda function
• Anonymous function that can have any number of arguments
• No name for function
• Function is defined at the time of call
• it can have only one expression
Eg: sum = lambda a,b: a+b
print ( sum (5,10))
2. Tuples

• Python Tuple is a collection of objects separated by commas.


• T1=( 1,2,3) t2= ( 3,7,0,-28, ‘xyz’, -11111.05)
• Tuple can contain items/elemets of different data types
• Once defined, it is not possible to modify elements- immutable
• To access elements, use indexing ( as in list)
immutable?
• Difference between List and Tuple?
- List is mutable, tuple is immutable
- List is defined with [ ], tuple is defined with ( )
Other features
• Most of the features are same as that of lists
a) slicing- access a portion of tuple
b) * for repetition
t1=(‘hi’)
print(t1*3)
c) + for concatenation
t1=(1,2,3) t2=( 3,4,5)
print(t1+t2)
( 1,2,3,3,4,5) - Duplication of elements is allowed
d) Negative indexing
- To access elements from the last position
t1[-1] gives the last item
e) Nesting- tuple as elements within another tuple
Slicing- examples
3. Sets
• S1={ 1, 2, 3,4}
• Curly braces are used to define sets
• Duplication of elements not allowed
• Items can be of any data type
• Set items are unordered, unchangeable, and do not allow duplicate
values.
• Set elements are not accessed using index/subscript
How to access elements?

How to add elements?


- Use add() function
• To remove an element,
t1.remove(‘banana’)
• To loop through set,
for item in t1:
print(item)
Set methods/functions
• Add(), remove()
• x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x. difference(y)
print(z)
o/p: { ‘cherry’, ‘banana’}
Those elements present in x but not in y
4. Dictionary
• Lists and tuple organizes elements by their position
• This is useful when we want to locate elements in order- 1st, 2nd,3rd,…
• In some situations, position of data is not significant, but data is
associated with some other element.
• Eg: ( Arun: 15, Gayathri: 16, Govind: 19)
( ‘Name’:’Arun’, ‘Roll no’: 15, ‘Marks’: 50)
-Related information
- Association between keys and values
• Dictionary is a data structure that stores data as ( key, value) pairs
• These pairs are called entries
• Entries are enclosed in {}, each key and its value is separated by
colon(:)

d1= {‘Name’:’Arun’, ‘Roll no’: 15, ‘Marks’: 50)


Dictionary operations
• How to create a dictionary?
d1={}  empty
d2={ ‘Arun’: 15, ‘Gayathri’: 16, ‘Govind’: 19} Name and rollno
information of a set of students
• How to add a new entry?
- To add a new ( name, Roll No) in d2
- d2[‘Karthik’]= 20
• d2= {‘Name’:’Arun’, ‘Roll no’: 15, ‘Marks’: 50}
To add branch info in d2
d2[ ‘branch’]= ‘ ECE’
print ( d2)
Op: {‘Name’:’Arun’, ‘Roll no’: 15, ‘Marks’: 50, ‘branch’: ‘ECE’}
• To replace a value in (key,value)
d2={‘Name’:’Arun’, ‘Roll no’: 15, ‘Marks’: 50, ‘branch’: ‘ECE’}
To change branch into EEE
>>> d2[‘branch’] = ‘EEE’
To access a value associated with key?
• d2={‘Name’:’Arun’, ‘Rollno’: 15, ‘Marks’: 50, ‘branch’: ‘ECE’}
To know the Roll number of Arun,
Print( d2[‘Rollno’])
If you do not know whether a key ( Marks) is present in d2. If present,
then you want its value to be printed.
>>> print( d2.get(“Marks”, None))
o/p: 50
>>> print( d2.get(“ Address”))
o/p: None ( as address field is not present in d2)
update() to change the value of key

To remove (key,value) from d


Looping through dict
• Also known as traversing a dictionary
• Reading element by element
d2={‘Name’:’Arun’, ‘Rollno’: 15, ‘Marks’: 50, ‘branch’: ‘ECE’}
1) for key in d2:
print(key, d2[key])
o/p: [ (Name’,’Arun’), (‘Rollno’ , 15), (‘Marks’, 50), (‘branch’, ‘ECE’)]
2) d2.items()
3) for(key,value) in d2.items():
print( key,value)
• len(d)  gives the number of entries
• list(d.keys()) - gives list of keys in the dictionary
• list(d.values()) list of all values in dictionary

You might also like