Apr. 07, 2013

List Manipulation in Python

Overview

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
value.

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()
Creation
L = ['yellow', 'red', 'blue', 'green', 'black']

>>>print L
returns: ['yellow', 'red', 'blue', 'green', 'black']
Accessing / Indexing
L[0]  = returns 'yellow'
Slicing
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
L.append("pink")

>>> 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
L.extend(L2)
Remove - remove first item in list with value "white"
L.remove("white")

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

Remove an item from a list given its index instead of its value
del.L[0]

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

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

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

Search list and return number of instances found
L.count('red')
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

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.

 



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.