In this blogs, we will look at some of the list methods. List is the collection of items of different data types. List can include string, integer and other data type values.
Reverse Method
Reverse method reverses items or elements in a list. Syntax listname.reverse().
In the example below, we have created a list which include numbers from 1 to 6. Displaying list items before reversing the order.
Then using reverse method to reverse the order of items in a list and print it.
num = [1,2,3,4,5,6]
print("Before reverse")
print(num)
num.reverse()
print("After reverse")
print(num)
Output
Before reverse
[1, 2, 3, 4, 5, 6]
After reverse
[6, 5, 4, 3, 2, 1]
Pop Method
Pop method removes last item from a list. Syntax listname.pop()
Using the num list which was created earlier. Displaying original items of a list. Using pop method to remove last item from a list and displaying the list items
num = [1,2,3,4,5,6]
print("Original List")
print(num)
num.pop()
print("Using pop method to remove last item from a list")
print(num)
Output
Original List
[1, 2, 3, 4, 5, 6]
Using pop method to remove last item from a list
[1, 2, 3, 4, 5]
Count method
This method counts number of occurrence of item in a list.
Created a list of numbers. We will be using count method to know number of times item 1 appeared in a list.
num = [1,2,3,4,5,6,2,4,5,61,2,1,66,1]
print(num.count(1))
Output
3
Remove method
Remove method removes the first occurrence of a value. Syntax listname.remove(value)
Below is the number list created which include some item appearing multiple times. For example, value 1 is appeared 3 times in a list. If we use remove method to remove value 1,it will remove only the first occurrence of a list.
num = [1,2,3,4,5,6,2,4,5,61,2,1,66,1]
print("Original list")
print(num)
num.remove(1)
print("After using remove method")
print(num)
Output
Original list
[1, 2, 3, 4, 5, 6, 2, 4, 5, 61, 2, 1, 66, 1]
After using remove method
[2, 3, 4, 5, 6, 2, 4, 5, 61, 2, 1, 66, 1]