0

I been reading What does the Star operator mean?, but I can't understand how the numbers come in. Could you explain to me the next expression:

squares = [x**2 for x in range(10)]

It's taken from the docs v3.5

Community
  • 1
  • 1
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
  • 3
    Read up on [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk). – Ami Tavory Sep 18 '16 at 15:40
  • 1
    It's the power operator. `x**2` means *`x` squared*, while `x**3` means *`x` to the third power*. Some languages use `^` instead (e.g. `x^2` for `x` squared) but in Python `^` is the XOR bit operator. It's **completely** unreleated to the use of `**` or `*` in `f(**arguments)`. – Bakuriu Sep 18 '16 at 15:45

2 Answers2

3

This is x raised to the power 2.

Expanded out, the list comprehension has the meaning:

 x_2 = []
 for x in range(0,10):
    x_2.append(x**2)  # Take x to the power 2
nbryans
  • 1,507
  • 17
  • 24
1
* # is the multiplication operator expression:

** # power operator so 3**2 = 9

Below is a list comprehension:

[f(x) for x in iterator]

so it creates a list with f(x)'s for each x as returned by the iterator

In this case f(x) = raising to the power of 2

range(10) are the numbers 0-->9

so for each number it will return that number raised to the power of 2

evan54
  • 3,585
  • 5
  • 34
  • 61