-2

I am a newbie for python and trying to understand the below piece.

[i**+1 for i in range(3)]

I know that i += 1 means i = i + 1 but what does **+ mean? I know ** means exponent but the output of the above list comprehension puzzling me.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Mahesh
  • 75
  • 2
  • 9
  • [Sometimes “i += x” is different from “i = i + x” in Python](https://stackoverflow.com/q/15376509/8881141) – Mr. T Jan 30 '18 at 12:11
  • @Piinthesky this question is not really relevant. The `+` here is a unary operator. – DeepSpace Jan 30 '18 at 12:13
  • @DeepSpace Not for the list comprehension and not for the example given, but why not point out that this assumed equivalence is sometimes a misconception? – Mr. T Jan 30 '18 at 12:21

2 Answers2

5

This confusion is a result of not surrounding operators with whitespaces as PEP8 suggests.

[i**+1 for i in range(3)] is the same as [i ** +1 for i in range(3)] which is the same as [i ** 1 for i in range(3)].

The output of [i**+1 for i in range(3)] is [0, 1, 2] which is the expected output.

**+1 is simply ** +1 which is the 1st positive power. The + is redundant here.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

This is similar to: i to the power of 1 i.e +1

[i**+1 for i in range(3)]

NOTE: +1 is not an addition here. it is the power of i

i.e.

   o to the power of +1 = 0;

   1 to the power of +1 = 1;

   2 to the power of +1 = 2;

so the answer is: [0, 1, 2]