HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Python List Methods


some common methods that can be used with lists in Python:


append():

Adds an element to the end of the list.

Example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]
               
           

extend():

Extends the list by appending elements from another iterable.

Example
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list)  # Output:  [1, 2, 3, 4, 5, 6]

             
           

insert():

Inserts an element at a specified position.

Example
my_list = [1, 2, 3]
my_list.insert(1, 1.5)
print(my_list)  # Output: [1, 1.5, 2, 3]

            
           

remove():

Removes the first occurrence of a specified value.

Example
my_list = [1, 2, 3 2 ]
my_list.remove(2)
print(my_list)  # Output: [1, 3, 2]

             
           

pop():

Removes the element at the specified position and returns it.

Example
my_list = [1, 2, 3]
popped_element=my_list.pop(1)
print(my_list)  # Output: [1, 3 ]

print(popped_element)   # Output: 2
            
           

index():

Returns the index of the first occurrence of a specified value.

Example
my_list = [1, 2, 3, 2]
index=my_list.index(2)
print(index)   # Output: 1

              
           

count():

Returns the number of occurrences of a specified value.

Example
my_list = [1, 2, 3, 2]
count = my_list.count(2)
print(count)  # Output: 2


              
           

sort():

Sorts the list in ascending order.

Example
my_list = [3, 1, 2]
my_list.sort()
print(my_list)  # Output: [1, 2, 3]

              
           

reverse():

Reverses the elements of the list in place.

Example
my_list = [1, 2, 3]
my_list.reverse()
print(my_list)  # Output:  [3, 2, 1]