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)

Leone Learning Systems, Inc. (LLS) is a North Shore company that provides online courses for kids anywhere and local teaching and tutoring services for students in Chicago and the Northern Suburbs of Chicagoland. LLS also provides a free geometry software package for children age 6 and up, and free resources for teachers and parents. This site includes information about classes taught, availability for tutoring, learning activities for kids, lesson plans, and ongoing software and curriculum research and development efforts.