Python Concepts/List Comprehension

Objective

 * To understand and use List Comprehensions, including Nested List Comprehensions.

Lesson
To create a list of squares of numbers in we can do something like: This approach has the perhaps undesirable side-effect of creating or re-assigning both and  It would be convenient if we could do something like: If we change the syntax slightly, List Comprehensions come to the rescue.

List Comprehensions
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Consider the task mentioned above, to create a list of squares of numbers in  Modify the syntax slightly, and put it into the form of a List Comprehension or "listcomp": In the listcomp above,  is local to the listcomp, and the final bracket   tells python that it should expect no more input.

A list comprehension consists of brackets containing an expression followed by a  clause, then zero or more   or   clauses. The result will be a new list. Consider some examples:

Given:

Display the position and value of all odd numbers in list :
The listcomp above is equivalent to:

Display all numbers in list that are an exact integer power of  :
The above listcomp is equivalent to:

Create a list of random positive integers:
Successive invocations of the above produce:

Nested List Comprehensions
Create a useful list:

New list of 3 rows
Create a list containing three rows in which each row contains every third value of

The nested listcomp above is equivalent to: Fill each row as necessary so that all rows have same length: The syntax of the listcomp requires a  statement. The second  statement above assigns a specific value to  either   or

Create a dictionary
Create a dictionary from a list in which each value at an even position is a key and each value at an odd position is the associated value:

Create a list containing two rows in which the first row contains keys and the second contains values. Fill as necessary: Transpose rows and columns and create input to dictionary:

List d is equivalent to: List d1 is equivalent to:

Listcomps simplified
In practice this code will do the job:

List Comprehensions for free-format Python
Although a listcomp recognizes statements beginning with only  or  , with a little dexterity the equivalent of assignments and  statements can be contained within a   The advantage is that a listcomp accepts free-format Python.

A "Unix date" has format

$ date Wed Feb 14 08:24:24 CST 2018

The code in this section uses list comprehensions to recognize valid dates. All of the following are considered valid dates:

Wed Feb 14 08:24:24 CST 2018 Wednes Feb 14 08:24:24 CST 2018 # More than 3 letters in name of day. Wed Febru 14 08:24:24 CST 2018 # More than 3 letters in name of month. Wed Feb 14 8:24 : 24 CST 2018 # White space in hh:mm:ss. wed FeB 14 8:24 : 24 cSt 2018 # Bad punctuation.

Build dictionary

Display dictionary

months['Jan'] = {'Januar', 'Janua', 'Janu', 'Jan', 'January'} months['Feb'] = {'Februa', 'Febru', 'Februar', 'Feb', 'Febr', 'February'} months['Mar'] = {'Mar', 'March', 'Marc'} months['Apr'] = {'April', 'Apri', 'Apr'} months['May'] = {'May'} months['Jun'] = {'June', 'Jun'} months['Jul'] = {'Jul', 'July'} months['Aug'] = {'Augus', 'Augu', 'Aug', 'August'} months['Sep'] = {'Sep', 'Septemb', 'September', 'Septem', 'Septe', 'Septembe', 'Sept'} months['Oct'] = {'Octo', 'Octobe', 'Oct', 'Octob', 'October'} months['Nov'] = {'Nove', 'November', 'Novemb', 'Novem', 'Nov', 'Novembe'} months['Dec'] = {'Decembe', 'Decemb', 'Dece', 'Decem', 'December', 'Dec'}

Build dictionary

Display dictionary

days['Sun'] = {'Sund', 'Sunda', 'Sun', 'Sunday'} days['Mon'] = {'Monday', 'Mon', 'Mond', 'Monda'} days['Tue'] = {'Tuesda', 'Tues', 'Tuesday', 'Tue', 'Tuesd'} days['Wed'] = {'Wednesda', 'Wednesd', 'Wedn', 'Wednes', 'Wed', 'Wedne', 'Wednesday'} days['Thu'] = {'Thursday', 'Thur', 'Thu', 'Thursd', 'Thurs', 'Thursda'} days['Fri'] = {'Friday', 'Fri', 'Frida', 'Frid'} days['Sat'] = {'Saturday', 'Satu', 'Saturda', 'Sat', 'Saturd', 'Satur'}

The regular expression:

Dictionary that contains number of days per month:

List all valid dates in string  below.

The list comprehension that does it all:

<_sre.SRE_Match object; span=(2, 35), match='MON Februar 12 0:30 : 19 CST 2018'> MON Februar 12 0:30 : 19 CST 2018 {'day': 'MON', 'month': 'Februar', 'date': '12', 'hours': '0', 'minutes': '30', 'seconds': '19', 'time_zone': 'CST', 'year': '2018'}

<_sre.SRE_Match object; span=(159, 255), match='Thursda              feb             29         > Thursda              feb             29                  00:30:19           CST            1944 {'day': 'Thursda', 'month': 'feb', 'date': '29', 'hours': '00', 'minutes': '30', 'seconds': '19', 'time_zone': 'CST', 'year': '1944'}

Further Reading or Review

 * Previous Lesson: With statement
 * This Lesson:List Comprehension
 * Next Lesson: Other statements
 * Course Home Page