While looking at the "Hidden Features of Python" page on StackOverflow, I found some really cool ones, and I wanted to share the coolest 8 with you. There are a bunch of other cool ones, so check out the page above.
- Chain comparison
Pretty cool; the last one means (20 == x) and (x > 4).
>>> x = 20 >>> 10 < x < 100 True >>> x < 30 < 10 * x < 300 True >>> 20 == x > 4 True
- Step in slice
>>> z = [0,1,2,3,4,5,6,7,8,9,10] >>> z[0:6:2] [0, 2, 4] >>> z[::-2] [10, 8, 6, 4, 2, 0] >>> k = range(100) >>> k[3:50:4] range(3,50,4)
Basically, the third parameter added a step, and the default is one.
- For...else
If the for loop is never broken it will go to the else statement. Obviously you could do the code below more efficiently, (10 in array) but that is just an example to what it could do.
for i in array: if i == 10: break else: print("10 wasn't in the list")
- In line value assignment / in-place value swapping
In line, you can separate
>>> a = 10 >>> b = 4 >>> a,b = b,a >>> a,b (4, 10) >>> a,b = 123, a * 20 >>> a,b (123, 80)
- Conditional Assignment
>>> y = 40 >>> x = 1 if (y == 30) else 4 >>> x 4 >>> y = 1 >>> x = 2 if (y == -1) else 2 if (y == 1) else 4 >>> x 2
As shown above, you can assign variables conditionally. In addition, you can call functions or classes conditionally:
>>> (func1 if x == 6 else func2)(6)
So, it shows how given a certain scenario, you can call certain function or classes. It is much shorter to write that than if x == 6: func1(6) ...
- Named Formatting
Named formatting is really cool. It allows you to format strings like this.
>>> print("%(language)s is %(adj)s"%{'language':'Python','adj':'cool'}) Python is cool
Instead of regular formatting, which puts the text in a separate format, named formatting replaces the formatted words with the result. You can also do this with variables already in your file by doing print("example"%locals())
- Operator Overloading for Set Operations
This is pretty cool; You can make a list a set, which makes it a list of all distinct values. Here are the operations:
a = set([1,2,3,4]) b = set([3,4,5,6]) a | b #set union {1, 2, 3, 4, 5, 6} a < b #a is a subset of b False a - b # set difference {1, 2} a ^b #Symmetric Difference {1, 2, 5, 6}
- Tuple Unpacking
>>> a, b , *c = (1,2,3,4,5,6,7,8,9,10) >>> a 1 >>> b 2 >>> c (3,4,5,6,7,8,9,10)
You can even make the list in the middle of the two variables, so a, *b, c would make a and c integers, while b is (2,3,4,5,6,7,8,9)
So, those are some cool features. There are plenty other cool and useful features, and you can check them out on Stackoverflow (link above).