Skip to content

List Generators

rollynoel edited this page Jun 16, 2013 · 2 revisions

Added by Rodrigo B. de Oliveira

List generators aka list comprehensions and list displays provide a quick way to create a list with selected elements from any enumerable object.

List generators are defined through the following syntax:

[element for item in enumerable]
[element for item in enumerable if condition]
[element for item in enumerable unless condition]

Some examples will help ilustrate the concept:

List with all the doubles from 0 to 5 (exclusive)

doubles = [i*2 for i in range(5)]

List with the names of the customers based on Rio de Janeiro

rjCustomers = [customer.Name for customer in customers if customer.State == "RJ"]
Clone this wiki locally