Python Basics

Understanding Python List Comprehensions

Python is a High Level language that allows users to create functional software in a fraction of the time it takes in Functional programing languagues

List Comprehensions : A list comprehension is a syntantic construct available in some programming languages such as python for creating a list based on existing lists.

  • List comprehensions are a one line For Loop that return a list of objects
  • Lists are an iterable object in the Python language

The list is the most versatile datatype in Python and can be written using the "[" brackets character for opening the list and "]" for closing it, with "," commas seperating the values inside.

  • Below is an example of a list containing a few intergers

In [3]:
MY_LIST = [1,2,3,4,5,6,7,8,9,10]

*Above we save the list to the variable MY_LIST so that when we want to access it we can just call it or use the print statement to display it.


In [4]:
print MY_LIST


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Notice the list displayed the numbers sequence 1 through 10. Below I will explain how a FOR LOOP can iterate through this list and multiply our saved values by 2 and save it to a new variable called NEW_LIST


In [5]:
NEW_LIST = []
for n in MY_LIST:
    NEW_LIST.append(n * 2)

In [6]:
print NEW_LIST


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

When we printed our new list, notice how all the values of the MY_LIST are multiplied by 2.

Now we can explain List Comprehensions and how we can take our for loop and condense it into one line.


In [7]:
A_LIST_COMPREHENSION = [n*2 for n in MY_LIST]

In [8]:
print A_LIST_COMPREHENSION


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Above, we created a list comprehension and notice how the values are the same as the values returned by our two line for loop.

Now that you are experience with list comprehensions, open up your Python Development Environment or IDLE and being to make your own list comprehensions. **See how fun they are!!**