Methods of python list

Author: Al-mamun Sarkar Date: 2020-03-24 20:16:51

Python list functions. Append item, Insert item, extend a list, add two lists, print list, delete an item from a list, pop item from the list. Pythons

List of Python list's methods:

Method Description
append() Used to add a new item at the end of the list
clear() Delete all the items from the list
copy() Create a new copy of the list
count() Returns the number of items with the given value
extend() Add two list
index() Used to get the index of the first item with the given value
insert() Used to add an item at the specified position
pop() Removes the element at the specified position
remove() Used to delete the item with the given value
reverse() Used to reverses the order of the list
sort() Used to sort the list in ascending and descending order

 

Code:

l = ['one', 'two', 'three', 'four']
print (l[1])
print (l[1:3])
print (l[:4])
print (l[2:])

print(type(l))

l[1] = 2
print (l[1])
l.append('five')
print (l)

l.insert(2, 'new')
print(l)

l.extend(['six', 'seven'])
print(l)

l = l + ['eight', 'nine']
print (l)

del l[2]
print(l)

l.remove('five')
print(l)

del l[-1]
print(l)

l.pop()
print(l)

 

Output:

two
['two', 'three']
['one', 'two', 'three', 'four']
['three', 'four']

2
['one', 2, 'three', 'four', 'five']
['one', 2, 'new', 'three', 'four', 'five']
['one', 2, 'new', 'three', 'four', 'five', 'six', 'seven']
['one', 2, 'new', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
['one', 2, 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
['one', 2, 'three', 'four', 'six', 'seven', 'eight', 'nine']
['one', 2, 'three', 'four', 'six', 'seven', 'eight']
['one', 2, 'three', 'four', 'six', 'seven']

 

Count, Len, reverse, sort function of the list:

l = ['one', 'two', 'three', 'four', 'two', 'a']

print(len(l))
print(l.count('two'))

l.reverse()
print(l)

l.sort()
print(l)

Output:

6
2
['a', 'two', 'four', 'three', 'two', 'one']
['a', 'four', 'one', 'three', 'two', 'two']