开发者

What does << do in Python?

开发者 https://www.devze.com 2023-03-16 17:00 出处:网络
I solved a problem on Project Euler but it took about 4 min开发者_如何学运维utes to run, which is above the recommended time, so I was looking through the different solutions in the forum.One of them

I solved a problem on Project Euler but it took about 4 min开发者_如何学运维utes 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

0

精彩评论

暂无评论...
验证码 换一张
取 消