Click for All Topics
x
to the end of the list.
my_list = [1, 2, 3]
print('original list:',my_list)
my_list.append(4)
print('modified list:',my_list)
# Output -
# original list: [1, 2, 3]
# modified list: [1, 2, 3, 4]
list.extend(iterable):
my_list = [1, 2, 3]
print('Original list:',my_list)
my_list.extend([4, 5, 6])
print('Modified list:',my_list)
# Output -
# Original list: [1, 2, 3]
# Modified list: [1, 2, 3, 4, 5, 6]
list.insert(i, x):
x
at the specified position i
.
my_list = [1, 2, 3]
print('Original list:',my_list)
my_list.insert(1, 4) # Inserts 4 at index 1
print('Modified list:',my_list)
# Output -
# Original list: [1, 2, 3]
# Modified list: [1, 4, 2, 3]
list.remove(x):
x
from the list.
my_list = [1, 2, 3, 2]
print('Original list:',my_list)
my_list.remove(2) # Removes the first occurrence of 2
print('Modified list:',my_list)
# Output -
# Original list: [1, 2, 3, 2]
# Modified list: [1, 3, 2]
i
. If i
is not provided, removes and returns the last element.
my_list = [1, 2, 3]
print('Original list:',my_list)
popped_value = my_list.pop(1) # Removes and returns the element at index 1
print('Modified list:',my_list)
# Output -
# Original list: [1, 2, 3]
# Modified list: [1, 3]
list.clear():
my_list = [1, 2, 3]
print('Original list:',my_list)
my_list.clear() # Removes all elements
print('Modified list:',my_list)
# Output -
# Original list: [1, 2, 3]
# Modified list: []
list.index(x[, start[, end]]):
x
in the list.
my_list = [1, 2, 3, 2]
print('Original list:',my_list)
index = my_list.index(2) # Returns the index of the first occurrence of 2
print('Index of 2:',index)
# Output -
# Original list: [1, 2, 3, 2]
# Index of 2: 1
list.count(x):
x
in the list.
my_list = [1, 2, 3, 2]
print('Original list:',my_list)
count = my_list.count(2) # Returns the number of occurrences of 2
print('count of 2:',count)
# Output -
# Original list: [1, 2, 3, 2]
# count of 2: 2
list.sort(key=None, reverse=False):
key
and reverse
are optional parameters.
my_list = [3, 1, 4, 1, 5, 9, 2]
print('Original list:',my_list)
my_list.sort() # Sorts the list in ascending order
print('Modified list:',my_list)
# Output -
# Original list: [3, 1, 4, 1, 5, 9, 2]
# Modified list: [1, 1, 2, 3, 4, 5, 9]
list.reverse():
my_list = [1, 2, 3]
print('Original list:',my_list)
my_list.reverse() # Reverses the list in place
print('Modified list:',my_list)
# Output -
# Original list: [1, 2, 3]
# Modified list: [3, 2, 1]
list.copy():
my_list = [1, 2, 3]
print('Original list:',my_list)
new_list = my_list.copy() # Creates a shallow copy of the list
print('Copied list:',my_list)
# Output -
# Original list: [1, 2, 3]
# Copied list: [1, 2, 3]
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India