Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Lists
  6. List Methods

List Methods

Built in Methods for the list,

len

Returns length of the string.

Syntax

len(list)

Example

>>> list1 = [2,4,5,6]
>>> print(len(list1))
4

max

Returns the item that has maximum value in the list

Syntax

max(list)

Example

>>> list1=[9,4,14,5]
>>> max(list1)

min

Returns the item that has minimum value in the list

Syntax

min(list)

Example

>>> list1=[9,4,14,5]
>>> min(list1)
4

list

Converts a sequence (list, tuple, string) to list

Syntax

list(seq)

Example

>>> tup1=(1,2,3,'a',4.5)
>>> list(tup1)
[1, 2, 3, 'a', 4.5]
>>> str1="hello"
>>> list(str1)
['h', 'e', 'l', 'l', 'o']

append

Adds the item to the end of the list

Syntax

list.append(item)

Example

>>> list1=[5,4,6]
>>> list1.append(10)
>>> list1
[5, 4, 6, 10]

count

Returns number of times the item occurs in the list

Syntax

list.count(item)

Example

>>> list1=[5,4,5,5,5,6,7]
>>> list1.count(5)
4

extend

Adds the elements of the sequence (list, string, tuple) at the end of the list

Syntax

list.extend(seq)

Example

>>> str1="Python"
>>> list1=[2,3,4]
>>> list1.extend(str1)
>>> list1
[2, 3, 4, 'P', 'y', 't', 'h', 'o', 'n']

index

Returns the index of the item. If item appears more than one time, it returns the lowest index

Syntax

list.index(item)

Example

>>> list1 = [5,4,5,5,6,7]
>>> list1.index(5)
0

insert

Inserts the given item at the specified index while the elements in the

Syntax

list.insert(index, item)

Example

>>> list1=[5,4,3]
>>> list1.insert(1,10)
>>> list1
[5, 10, 4, 3]

pop

Deletes and returns the last element in the list

Syntax

list.pop( )

Example

>>> list1=[4,5,3,6,1]
>>> list1.pop()
1
>>> list1
[4, 5, 3, 6]

Deletes and returns the element at the specified position

Syntax

list.pop(index)

Example

>>> list1 = [5,4,7,8]
>>> list1.pop(1)
4
>>> list1
[5, 7, 8]

remove

Deletes the given item from the list

Syntax

list.remove(item)

Example

>>> list1 = [5,4,6,7]
>>> list1.remove(6)
>>> list1
[5, 4, 7]

reverse

Reverses the position of the items in the list

Syntax

list.reverse( )

Example

>>> list1=[5,4,6,1,7]
>>> list1.reverse()
>>> list1
[7, 1, 6, 4, 5]

sort

sort( ) method arranges the list of elements in ascending order

Syntax

list.sort( )

Example

>>> list1 = [ 2,3,1,4,7,6,5]
>>> list1.sort()
>>> list1
[1, 2, 3, 4, 5, 6, 7]

clear

Removes all the elements from the list

Syntax

list.clear( )

Example

>>> list1
[1, 2, 3, 4, 5, 6, 7]
>>>
>>> list1.clear()
>>> list1
[]

del

Deletes the entire list

Syntax

del(list)

Example

>>> list2=[5,4,3]
>>> del(list2)
>>> list2
NameError: name 'list2' is not defined

Loading

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments