Apr. 07, 2013

List Manipulation in Python


List is one of the simplest and most important data structures in Python. 

Lists are enclosed in square brackets [ ] and each item is separated by a comma.  

Lists are collections of items where each item in the list has an assigned index

A list is mutable, meaning you can change its contents.

Lists are very ?exible and have many built-in control functions.

Methods of List objects

Calls to list methods have the list they operate on appear before the method
name separated by a dot, e.g. L.reverse()
L = ['yellow', 'red', 'blue', 'green', 'black']

>>>print L
returns: ['yellow', 'red', 'blue', 'green', 'black']
Accessing / Indexing
L[0]  = returns 'yellow'
L[1:4]  = returns ['red', 'blue', 'green']
L[2:] 	= returns ['blue', 'green', 'black']
L[:2] 	= returns ['yellow', 'red']
L[-1]  	= returns 'black'
L[1:-1] = returns ['red', 'blue', 'green']
Length - number of items in list
len(L)  = returns 5
Sorting - sorting the list
sorted(L) = returns ['black', 'blue', 'green', 'red', 'yellow']
Append - append to end of list

>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']
Insert - insert into list
L.insert(0, "white")

>>> print L
returns: ['white', 'black', 'blue', 'green', 'red', 'yellow', 'pink']
Extend - grow list
Remove - remove first item in list with value "white"

>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']

Remove an item from a list given its index instead of its value

>>> print L
['blue', 'green', 'red', 'yellow', 'pink']

Remove last item in the list
L.pop()  = returns 'pink'

# remove indexed value from list
L.pop(1) = returns 'green'  
Reverse - reversing the list

Search list and return number of instances found
Keyword "in" - can be used to test if an item is in a list
if 'red' in L:
    print "list contains", 'red'
For-in statement - makes it easy to loop over the items in a list
for item in L:
    print item

L = ['red', 'blue', 'green']
for col in L:
    print col

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.