What are list comprehensions?

A list comprehension is like a super-fast robot that helps you make lists by doing simple tasks over and over again.

Imagine you have a bag of 10 jellybeans, and you want to put each one into a tiny cup. Instead of doing it one by one, you could use a list comprehension, it’s like telling the robot: “Take every jellybean from the bag and put it in a cup.” In no time, your robot has filled all 10 cups!

How It Works

Let’s say you have numbers 1 to 5, and you want to double them. A list comprehension is like saying: “Take each number and multiply it by 2.”

Instead of writing:

[1*2, 2*2, 3*2, 4*2, 5*2]

You write something like this:

[x*2 for x in [1, 2, 3, 4, 5]]

This is easier to read and faster to type, just like how your robot works!

Why It's Cool

It’s not magic, it’s just a neat way to repeat simple tasks. You can use it with numbers, letters, even words! It helps you create new lists quickly, like stacking blocks in a fun pattern.

Take the quiz →

Examples

  1. Creating a list of even numbers from 1 to 10 using a simple formula.
  2. Making a list of squared numbers quickly without writing multiple lines of code.
  3. Turning a sentence into a list of individual words with one line.

Ask a question

See also

Discussion

Recent activity