Course Home
Announcements
Check Yourself
Python Errors in English
CodeSkulptor FAQ
Reflections

Online Lessons

Related Links

Online Development

Lessons

Reference

eBooks

List Comprehensions

I added this page because list comprehensions come up in advanced lessons in CodeAcademy and there's some optional material on list comprehensions in the Google Python Course. It will also help you understand some of the CodeAcademy lessons on list slicing.

List Comprehensions (optional)

The material in this section is from this page of the Google Python Course

List comprehensions are a more advanced feature which is nice for some cases but is not needed for the exercises and is not something you need to learn at first (i.e. you can skip this section). A list comprehension is a compact way to write an expression that expands to a whole list. Suppose we have a list nums [1, 2, 3], here is the list comprehension to compute a list of their squares [1, 4, 9]:

  nums = [1, 2, 3, 4]

  squares = [ n * n for n in nums ]   ## [1, 4, 9, 16]

The syntax is [ expr for var in list ] -- the for var in list looks like a regular for-loop, but without the colon (:). The expr to its left is evaluated once for each element to give the values for the new list. Here is an example with strings, where each string is changed to upper case with '!!!' appended:

  strs = ['hello', 'and', 'goodbye']

  shouting = [ s.upper() + '!!!' for s in strs ]
  ## ['HELLO!!!', 'AND!!!', 'GOODBYE!!!']

You can add an if test to the right of the for-loop to narrow the result. The if test is evaluated for each element, including only the elements where the test is true.

  ## Select values <= 2
  nums = [2, 8, 1, 6]
  small = [ n for n in nums if n <= 2 ]  ## [2, 1]

  ## Select fruits containing 'a', change to upper case
  fruits = ['apple', 'cherry', 'bannana', 'lemon']
  afruits = [ s.upper() for s in fruits if 'a' in s ]
  ## ['APPLE', 'BANNANA']

CodeAcademy Lessons

Work through the following CodeAcademy lessons to further solidify your understanding:

Section: ADVANCED TOPICS IN PYTHON -> Advanced Topics in Pythons

Lessons

  • List Comprehensions (1-3)
  • List Slicing (7-11)