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.
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.
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
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
When we printed our new list, notice how all the values of the MY_LIST are multiplied by 2.
In [7]:
A_LIST_COMPREHENSION = [n*2 for n in MY_LIST]
In [8]:
print A_LIST_COMPREHENSION
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!!**