简体   繁体   中英

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?

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.

It's a binary bitwise shift operator.

x << n
x shifted left by n bits

x >> n
x shifted right by n bits

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM