gtmanfred
gtmanfred

Reputation: 593

What does << do in Python?

I solved a problem on Project Euler but it took about 4 minutes to run, which is above the recommended time, so I was looking through the different solutions in the forum. One of them included the symbol << in a list comprehension. This is what it looked like

blist.extend([(i << 1) + 3 for i in range(num) if alist.get(i)])  

I can't find anywhere what exactly this << symbol does. Can someone help me?

Upvotes: 6

Views: 6710

Answers (3)

user456814
user456814

Reputation:

It's a bit shift operator (Python docs), and is common among many programming languages, such as C, Java, PHP, etc. According to the Python docs:

They shift the first argument to the left or right by the number of bits given by the second argument.

A right shift by n bits is defined as division by pow(2, n). A left shift by n bits is defined as multiplication with pow(2, n). Negative shift counts raise a ValueError exception.

So in your specific case, i << 1 means left shift by 1 bit, which is equivalent to multiplying by 2^1, or just 2.

Upvotes: 10

db48x
db48x

Reputation: 3178

That's the left-shift operator. It shifts all of the bits in i to the left by 1 step, effectively multiplying i by 2.

http://docs.python.org/py3k/reference/expressions.html#shifting-operations

Upvotes: 1

George Johnston
George Johnston

Reputation: 32258

It's a binary bitwise shift operator.

x << n
x shifted left by n bits

x >> n
x shifted right by n bits

Upvotes: 1

Related Questions