List Comprehension

Overview


List comprehension is an easy way of generating a list, that can be described mathematically.


Example 1


If we wanted to generate a list of the odd numbers from 1 to 100, we could create this with the following list comprehension.
oddlist = [i for i in range(100) if not i % 2 ==0]
This returns:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]


Example 2


Here is another example, try to follow what it is doing.
examplelist = [x * 6 for x in range(5,20,2)]
Returns:
[30, 42, 54, 66, 78, 90, 102, 114]


Example Strings


If we have a string
S = "the boat is sinking"
We can use the split function to turn this sentence into a list of words
S = s.split()
This returns:
['the', 'boat', 'is', 'sinking']
We can the operate on this list to generate more lists.
s = 'The boat is sinking'
s = s.split()
s = [[i.upper(), i.lower(), i + " end"] for i in s]
print (s)
This returns:
[['THE', 'the', 'The end'], ['BOAT', 'boat', 'boat end'], ['IS', 'is', 'is end'], ['SINKING', 'sinking', 'sinking end']]



Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines