Professional Documents
Culture Documents
Lect-02 List
Lect-02 List
3
Prof. Harish D. Gadade, COEP Technological University, Pune
Accessing List Elements
● There are two ways of accessing list elements in python
○ List Index
○ Negative Index
4
Prof. Harish D. Gadade, COEP Technological University, Pune
Accessing List Elements
● List Index
a=[“Vihaan”,”Ahaan”,”Rihaan”,”Ayaan”]
print(a[0])
print(a[3])
print(a[1:3])
print(a[:])
print(a[:3]
print(a[1:]
a=[“Vihaan”,”Ahaan”,[10,20,30,40],”Rihaan”]
print(a[2][1])
5
Prof. Harish D. Gadade, COEP Technological University, Pune
Accessing List Elements
● Negative Index
a=[“Vihaan”,”Ahaan”,”Rihaan”,”Ayaan”]
print(a[-1])
print(a[-3])
print(a[-3:-1]
6
Prof. Harish D. Gadade, COEP Technological University, Pune
List Slicing
print(a[2:3])
print(a[:-2])
print(a[:])
7
Prof. Harish D. Gadade, COEP Technological University, Pune
Change/Modify Lists Elements
a[0]=100
print(a)
a[2:3]=[200,300]
print(a)
8
Prof. Harish D. Gadade, COEP Technological University, Pune
Add/Change Lists Elements
● We can add one item to the end of list using append() method or
can add several items using extend() method
a=[1,2,3,4]
a.insert(1,20)
print(a)
10
Prof. Harish D. Gadade, COEP Technological University, Pune
Deleting Lists Elements
● We can use remove() to remove the given item or pop() to remove an
item at the given index.
● The pop() method removes and returns the last item if the index is not
provided. This helps us implement lists as stacks (first in, last out
data structure).
a=[10,20,30,40,50]
a.remove(20)
print(a)
a.pop(2)
print(a)
a.pop()
print(a)
11
Prof. Harish D. Gadade, COEP Technological University, Pune
Python List Methods
● Python has many useful list methods that makes it really easy to work
with lists. Here are some of the commonly used list methods.
append() adds an element to the end of the list
a=list((“Vihaan”,”Ahaan”,10,20))
print(a)
Output:
[“Vihaan”,”Ahaan”,10,20]
13
Prof. Harish D. Gadade, COEP Technological University, Pune
Assignments
1. Write a python program to find maximum element from the list/array
elements
2. Write a python program to find second maximum elements from list/array
elements
3. Write a program to reverse the list / array elements
4. Write a program to search substring from a given list/array
14
Prof. Harish D. Gadade, COEP Technological University, Pune