List Method Part 1

List is a collection of items or elements. There are number of methods available to process list. Some of the methods are convers in this blogs

sum()

This method returns sum of all elements in a list

Syntax
sum(list)

Example

num = [1,2,3,4,5,6,7,8,9]
print(sum(num))

Output

45

pop()

Remove last element from a list

Syntax
list.pop()

Example

num = [1,2,3,4,5,6,7,8,9]
print('Original List')
print(num)
num.pop()
print('After using pop method to remove last element from a list')
print(num)

Output

Original List
[1, 2, 3, 4, 5, 6, 7, 8, 9]
After using pop method to remove last element from a list
[1, 2, 3, 4, 5, 6, 7, 8]

clear()

Deletes all element from a list

Syntax
list.clear()

num = [1,2,3,4,5,6,7,8,9]
print('Original List')
print(num)
num.clear()
print('Deleting all elements from a list')
print(num)

Output

Original List
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Deleting all elements from a list
[]

reverse()

Reverse the position of all elements in a list

Syntax
list.reverse()

Example

num = [1,2,3,4,5,6,7,8,9]
print('Original List')
print(num)
num.reverse()
print('Using reverse method to change position of elements')
print(num)

Output

Original List
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Using reverse method to change position of elements
[9, 8, 7, 6, 5, 4, 3, 2, 1]
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s