List Chaining and Permutations

Vlad Bezden
2 min readApr 25, 2017

--

List comprehension is very powerful high level and declarative mechanism to create lists in Python.

There are two ways of creating list comprehensions.

  1. Chaining
  2. Permutations (cross product)

Chaining:

Chaining is done with nested two or more list comprehensions but passing result of one list comprehension to another one.

For instance in an example below we have list of list (cars of cars in different categories). So in order to go through every car we have to go two times through the list:

  1. Get category that contains list of cars
  2. Go through each category and take individual car.
cars = [['Mustang', 'GT'],
['Explorer', 'Expedition'],
['F-150', 'Super Duty']]
# chaining example
chaining = [car.upper()
for category in cars
for car in category]

If we have variable overlap in for closes then we have ‘chaining’. In our example we have ‘category’ overlap. Result always will be the same number of items as in original list. So in our case we have six cars, so in the end we get six cars (assume we are not using filter)

['MUSTANG', 'GT', 'EXPLORER', 'EXPEDITION', 'F-150', 'SUPER DUTY']

Permutations or Cross Products:

We achieve that with two or more lists with no overlaps in for clause.

cars = [['Mustang', 'GT'],
['Explorer', 'Expedition'],
['F-150', 'Super Duty']]
# permutation/crossproduct
permutations = [(car, year)
for car in chaining
for year in range(2015, 2017)]

Here is an output of ‘permutations’. As you can see we have results from both lists and number of items we get back is multiplication of items from both lists (6 * 2 = 12)

[('MUSTANG', 2015), ('MUSTANG', 2016), ('GT', 2015), ('GT', 2016), ('EXPLORER', 2015), ('EXPLORER', 2016), ('EXPEDITION', 2015), ('EXPEDITION', 2016), ('F-150', 2015), ('F-150', 2016), ('SUPER DUTY', 2015), ('SUPER DUTY', 2016)]

Please notice that ordering in permutation/crossproduct matters. The final result of items will be the same, but sequence how they are produced will be different.

# ordering in permutation matters
permutations2 = [(car, year)
for year in range(2015, 2017)
for car in chaining]

Since now we have years in a first ‘for’ clause we get cross product for each year, where in example above we have crossproduct for each car

[('MUSTANG', 2015), ('GT', 2015), ('EXPLORER', 2015), ('EXPEDITION', 2015), ('F-150', 2015), ('SUPER DUTY', 2015), ('MUSTANG', 2016), ('GT', 2016), ('EXPLORER', 2016), ('EXPEDITION', 2016), ('F-150', 2016), ('SUPER DUTY', 2016)]
Example of how to create list comprehension using chaining and crossproduct

--

--