Python List Operations

1- List Search

index(): Returns the index of the specified data in the list
Syntax: list.index(data, start_index, end_index)
count(): Counts the occurrences of the specified data in the current list
len(): Number of items in the list
in: Checks if the specified data is in a list
not in: Checks if the data is not in a list
list1=["a","b","c","a","e","f"]
print(list1.index("c")) #2
print(list1.count("a")) #2
print(len(list1))   #6
print("H" in list1) #False
print("H" not in list1) #True

2- List Addition

append(): Adds data to the end of the list; if the data is a sequence, all items in that sequence are added to the list
extend(): Adds data to the end of the list; if the data is a sequence, each item in that sequence is added to the list one by one
insert(): Adds data at a specified position
Syntax: list.insert(index, data)
list1=["a","b","c"]
list2=["a","b","c"]
list3=["a","b","c"]
list1.append("123")
print(list1)    #['a', 'b', 'c', '123']
list1.append([1,2,3])
print(list1)    #['a', 'b', 'c', '123', [1, 2, 3]]
list2.extend("123")
print(list2)    #['a', 'b', 'c', '1', '2', '3']
list3.insert(1,"123")
print(list3)    #['a', '123', 'b', 'c']
3- List Deletion
del: Deletes the list or an item in the list
pop(): Deletes the data at the specified index; if no index is specified, deletes the last item. Returns the deleted data
remove(data): Removes the specified data
clear(): Clears all data in the list
str1 = ["a", "b", "c"]
str2 = ["a", "b", "c"]
str3 = ["a", "b", "c"]
str4 = ["a", "b", "c"]
del str1[1]
print(str1)  #['a', 'c']
resstr2 = str2.pop()
print(resstr2)  #c
print(str2)  #['a', 'b']
str3.remove("b")
print(str3)     #['a', 'c']
str4.clear()
print(str4) #[]
4- List Modification
Reverse: reverse()
Sort: sort()
Syntax: list.sort(key=None, reverse=False) Default is False for ascending, True for descending
# Modify data at specified index
str1=[1,2,3,4]
str2=[1,2,3,4]
str3=[1,3,2,4]
str4=[1,3,2,4]
str1[1]=123
print(str1) # [1, 123, 3, 4]
str2.reverse()
print(str2) # [4, 3, 2, 1]
str3.sort()
print(str3)  # [1, 2, 3, 4]
str4.sort(reverse=True)
print(str4)    # [4, 3, 2, 1]
5- List Traversal
While Traversal
str1=[1,2,3,4]
i=0
while i<len(str1):      print(str1[i])      i+=1
For Traversal
str1=[1,2,3,4]
for i in str1:      print(i)

Leave a Comment