Warning: sizeof(): Parameter must be an array or an object that implements Countable in /homepages/9/d213665487/htdocs/clickandbuilds/CoalGeology/wp-content/plugins/wordpress-firewall.php on line 245

Warning: sizeof(): Parameter must be an array or an object that implements Countable in /homepages/9/d213665487/htdocs/clickandbuilds/CoalGeology/wp-content/plugins/wordpress-firewall.php on line 245

Warning: Cannot modify header information - headers already sent by (output started at /homepages/9/d213665487/htdocs/clickandbuilds/CoalGeology/wp-content/plugins/wordpress-firewall.php:245) in /homepages/9/d213665487/htdocs/clickandbuilds/CoalGeology/wp-content/plugins/wp-super-cache/wp-cache-phase2.php on line 62
Some useful list methods in Python with examples – Coal Geology and Mining: Consulting Services

Some useful list methods in Python with examples

The following examples show you some of the most basic methods that you would use for a Python list object.

>>> #create a list
>>> #use numers as list items for simplicity
>>> alist=[1,2,3,4,5]
>>>
>>> #add an object 6 to the list using append method
>>> alist.append(6)
>>> alist
[1, 2, 3, 4, 5, 6]
>>>
>>> #Appends the items in the sequence [1] to the list.
>>> #insert 10 at [1]
>>> alist.insert(1,10) #(index,item)
>>> alist
[1, 10, 2, 3, 4, 5, 6]
>>>
>>> #count number of a particular object in the list
>>> alist.count(3)
1
>>> #Remove an item from the list
>>> alist.remove(10)
>>> alist
[1, 2, 3, 4, 5, 6]
>>>
>>> #remove the last item from the list
>>> alist.pop()
6
>>> alist
[1, 2, 3, 4, 5]
>>>
>>> #remove an item by its index
>>> alist.pop(0)
1
>>> alist
[2, 3, 4, 5]
>>>
>>> #reverse the list
>>> alist.reverse()
>>> alist
[5, 4, 3, 2]
>>>
>>> #sort the list
>>> alist.sort()
>>> alist
[2, 3, 4, 5]
>>>

Leave a Comment

Your email address will not be published. Required fields are marked *