Notes: List in Python
List: List (the built-in data type), in Python are the collection of ordered and changeable sequence or
records, represented by square brackets.
Create a List:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
Access Items:
We can access the List items by referring to the indexed number.
For example: To print the Kirst item of the List:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
print(Lst[0])
Output: Saksham
Negative Indexing:
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last item etc.
For example:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
print(Lst[-1])
Output: Lakshya
Change Items Value:
To change the value of a speciKic item, refer to the index number:
Change the second items:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
Lst[1]= 'Prashant'
print(Lst)
Output: ['Saksham', 'Prashant', 'Aayushman', 'Lakshya']
Loop through a List:
We can loop through the List items by using a for loop:
Print all items in the List, one by one:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
for x in Lst:
print(x)
Output:
Saksham
Arnav
Aayushman
Lakshya
Check if items Exists:
To determine if a speciKied items is present in a List use the in keyword:
Check if “Saksham” is present in the List:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
if 'Saksham' in Lst:
print ('Yes')
Output: Yes
List Length
To determine how many items a Lst has, use the len() function:
Print the number of items in the Lst:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
print(len(Lst))
Output: 4
Add Items
To add an item to the end of the List, use the append ( ) method:
Using the append ( ) method to append an item:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
[Link]('Awadesh')
print (Lst)
Output: ['Saksham', 'Arnav', 'Aayushman', 'Lakshya', 'Awadesh']
To add an item at the speciKied index, use the insert( ) method:
Insert an item as the second position:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
[Link](1, “Aashish”)
print (Lst)
Output: ['Saksham', 'Aashish', 'Arnav', 'Aayushman', 'Lakshya']
Remove Item
There are several methods to remove items from a List:
The remove() method removes the speciKied item:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
[Link](“Lakshya”)
print (Lst)
Output:['Saksham', 'Arnav', 'Aayushman']
The pop ( ) method removes the speciKied index, (or the last item if index is not speciKied):
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
[Link](1)
print (Lst)
Output: ['Saksham', 'Aayushman', 'Lakshya']
The clear ( ) method empties the List:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
[Link]()
print (Lst)
Output : [ ]
Copy a List:
The copy ( ) copy a List:
Lst=['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
NewLst=[Link]( )
print (NewLst)
Output: ['Saksham', 'Arnav', 'Aayushman', 'Lakshya']
Join Two Lists:
Joining a List with + Operator.
Lst1=["a","b","c"]
Lst2=[1,2,3]
Lst3=Lst1 + Lst2
print(Lst3)
Output: ['a', 'b', 'c', 1, 2, 3]