Take the 2-minute tour ×
    def different(s):
       x = len(s)
       for i in range(1, 1 << x):
          u.append([s[j] for j in range(x) if (i & (1 << j))])

It takes a list and makes different combinations (a,b,c) = ((a,b,c),(a,b),(a,c) etc..) But what does the range do? From 1 to what. I don't understand the "<<"

and also, if (i & (1 << j)) what does this do? it checks if i and 2 to the power of j?? doesn't make any sense to me :/

share|improve this question
Lots of people put effort into helping you out. Deleting this question would result in them losing rep. If your issue is solved by some other means, leave an answer with your solution and select it when the option becomes available. Helps people who have similar issues and doesn't penalize those that tried to help. (also fixed some stuff you were concerned about) –  Will Apr 11 '11 at 12:36
add comment

2 Answers

up vote 4 down vote accepted

The range function returns a list of numbers from zero to the given number minus one. It also has two- and three-argument forms (see the doc for more info):

range(n) == [0, 1, 2, ..., n - 1]

<< is the left-shift operator, and has the effect of multiplying the left hand side by two to the power of the right hand side:

x << n == x * 2**n

Thus the above range function (range(1, 1 << x)) returns [1, 2, 3, ..., 2**x - 1].

In the seconds usage of <<, the left-shift is being used as a bit-mask. It moves the 1-bit into the j-th bit, and performs a bit-wise and with i, so the result will be non-zero (and pass the if test) if and only if the j-th bit of i is set. For example:

j = 4
1 << j = 0b1000 (binary notation)

i = 41 = 0b101001
i & (1 << j) = 0b101001
             & 0b001000
             = 0b001000 (non-zero, the if-test passes)

i = 38 = 0b100110
i & (1 << j) = 0b100110
             & 0b001000
             = 0b000000 (zero, the if-test fails)

In short, x & (1 << y) is non-zero iff the y-th bit of x is set.

share|improve this answer
add comment

<< is the binary left shift operator. 1 << x is a way of saying two to the power of x.

share|improve this answer
so it's the same as 2**x? –  nils Mar 22 '11 at 8:45
@nils: Yes, pretty much. –  icktoofay Mar 22 '11 at 8:52
@nils, yes, but 3 << 10 is twice as fast as 3 * 2 ** 10 –  eumiro Mar 22 '11 at 9:10
@nils: "so it's the same as 2**x?"? Please actually try the code. Please run an experiment. Please execute it interactively at the Python >>> prompt. You can prove they're the same all by yourself. –  S.Lott Mar 22 '11 at 9:53
add comment

Your Answer


