DEV Community

Cover image for Lists Methods
datatoinfinity
datatoinfinity

Posted on

Lists Methods

Almost every software or technology revolves around four basic functions: Create, Retrieve, Update, and Delete—collectively known as CRUD operations.

Same is going with lists also, we are going to perform adding, modifying and retrieving method on list which is built in function.

1. append(): Basically it adds value at the end of the list.

a=[1,2,3]
a.append(4)
print(a)
Output:
[1, 2, 3, 4]

2. clear(): As name suggest it simply clear the list.

a=[1,2,3]
a.clear()
print(a)
[]

3. copy(): Basically copy the original list and we can make changes in copied list which doesn't effect the original one.

a=[1,2,3,5,6]
copy_a=a.copy()

copy_a.remove(6)
print(a)
print(copy_a)
Output:
[1, 2, 3, 5, 6]
[1, 2, 3, 5]

4. count(): It shows how many times specific value is been repeated.

a=[1,2,3,5,6,6,5,2,3,4,5,4,3]
elon=a.count(6)
print(elon)
Output:
2

5. extend(): It add two list.

fruits=['apple','cherry','banana']
fruits1=['orange','grapes','strawberry']
fruits.extend(fruits1)
print(fruits)
Output:
['apple', 'cherry', 'banana', 'orange', 'grapes', 'strawberry']

6. index(): It used to find the index of value in a list.

fruits=['apple','cherry','banana']
print(fruits.index('cherry'))
2

7. insert(): It is used for adding value in list with there position.

fruits=['apple','cherry','banana']
fruits.insert(1,'orange')
print(fruits)
Output:
['apple', 'orange', 'cherry', 'banana']

8. pop(): It will remove the value from the list according to its position.

fruits=['apple','cherry','banana']
fruits.pop(2)
print(fruits)
Output:
['apple', 'cherry']

9. remove(): It removes with help from there name and it remove first occurrence.

fruits=['apple','cherry','banana','cherry']
fruits.remove('cherry')
print(fruits)
Output:
['apple', 'banana', 'cherry']

10. reverse(): It reverse the order of the list.

fruits=['apple','cherry','banana','cherry']
fruits.reverse()
print(fruits)
['cherry', 'banana', 'cherry', 'apple']

11. sort(): sort the list in ascending order by default.

fruits=['apple','cherry','banana','cherry']
fruits.sort()
print(fruits)
['apple', 'banana', 'cherry', 'cherry']

Top comments (0)