Python tutorial- list common methods


Common methods of List

List Methods: append, extend, count, index, insert, pop, remove, reverse, and sort methods.

You can also append a new element to a list by using append() method:

>>> lst1.append(16)

>>> lst1

[12, 15, 16]

>>> 

To append a range of values to the list, use extend() method:

>>> lst1.extend([17,18,19])

>>> lst1

[12, 15, 16, 17, 18, 19]

>>> 

To count frequencies of an element in the list you will use count() method:

>>> lst1.count(15)

1

>>> 

To find index of an element, you can use index() method:

>>> lst1=[12,13,14,15]

>>> lst1.index(12)

0

>>> 

 

You can insert an object to any position of the list by using insert() method:

>>> lst1.insert(4,16)

>>> lst1

[12, 13, 14, 15, 16]

>>> lst1.insert(0,11)

>>> lst1

[11, 12, 13, 14, 15, 16]

>>> lst1.insert(2,'Hello')

>>> lst1

[11, 12, 'Hello', 13, 14, 15, 16]

>>> 

List also contains pop() method that lets you delete the last element of the list:

>>> lst1.pop()

16

>>> lst1

[11, 12, 'Hello', 13, 14, 15]

 

With remove() method, you can remove an item from the list starting from the beginning( left-to-right). If there are more than one the same items, the first left will be removed:

>>> lst1.remove(11)

>>> lst1

[12, 'Hello', 13, 14, 15]

>>> lst2=[11,12,14,11,11]

>>> lst2.remove(11)

>>> lst2

[12, 14, 11, 11]

>>> 

To reverse the display order of a list, use reverse() method:

>>> lst2.reverse()

>>> lst2

[11, 11, 14, 12]

>>> 

 

To sort the list, use sor() method:

>>> lst2.sort()

>>> lst2

[11, 11, 12, 14]

>>> 




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.