DEV Community

sanadiqbal
sanadiqbal

Posted on

PYTHON :LIST METHODS

Some of the most important python list methods are :

1.append() : Appends and add value to the end of list.

# Creating the list
l=[1,2,3]
a=5

# Append the value a to the list
l.append(a)
print(l)
# Output : [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

2.copy() : Returns a copy of the given list.

# List
l=[1,3,5]

# Copying the list value to a new list
l_copy=l.copy()
print(l_copy)
# Output : [1,3,5]
Enter fullscreen mode Exit fullscreen mode

3.count() :Returns the count of elements in the list.

#list
l=[1,7,9]
#using count
n=l.count()
print(n)
# Output : 3
Enter fullscreen mode Exit fullscreen mode

4.sort() :Sorts the list in ascending or descending order.

# list
l=[1,9,8,100]
# Sort in ascending order
l.sort()
#Sorting in descending order
l.sort(reverse=True)
Enter fullscreen mode Exit fullscreen mode

5.reverse() : Reverses the elements of list.

#list
l=[4,3,5,7]
#reversing the list
l.reverse(l)
print(l)
# Output : [7,5,3,4]
Enter fullscreen mode Exit fullscreen mode

6.remove() : Removes the occurrence of the first given value from the list.

# list
l=[2,2,2]
# removing 2 from the list
l.remove(2)
print(l)
# Output : [2,2]
Enter fullscreen mode Exit fullscreen mode

7.pop() : Pops and returns the value of the given argument.If no value is passed,it pops and returns the value at last index.

# list 
l=[2,4,5,7]
# Popping the value at index 1 and storing it in a
a=l.pop(1)
print(a)
# Output : 4
Enter fullscreen mode Exit fullscreen mode
  1. remove() : Removes the first occurrence of the given element from the list.
# list
l=[2,3,4,2]

# Removing 2 from the list
l.remove(2)
print(l)
# Output : [3,4,2]
Enter fullscreen mode Exit fullscreen mode

9.insert() : Inserts the given value at the given index.

#list
l=[9,8,7]
# inserting 0 at index 1
l.insert(0,1)
print(l)
# Output : [9,0,8,7] 
Enter fullscreen mode Exit fullscreen mode

10.index() : Returns the lowest index where the element appears.

#list 
l=[2,0,8,2]
# Getting the lowest index of 2
a=l.index(2)
print(a)
# Output : 0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)