10 lesser-known facts about python
- Python is the only language to have an else condition for a “for loop”. It executes if the for loops terminates normally without any “break”.
The else will be fired if there’s no even number on the list.
2. You can assign () to [], but not the other way round.
The reason is [] is an empty list and () is an empty tuple. Tuples are immutable meaning you can’t change them once created.
3. Python uses indentation to mark blocks whereas other languages use braces. If you run “from __future__ import braces”, you’ll get -
it’s a joke, meaning even in the future, Python won’t use braces.
4. You can assign different values to different variables at the same time.
As you can see, a gets the value 1 and b gets the value 2.
5. To swap variables in other languages, you need to have a temporary variable and do it like this.
In python, you can just do this,
a, b = b, a
6. You can return multiple values at the same time.
Actually, Python is not returning more than one value. It’s actually returning a tuple, which gets unpacked.
7. You can quickly reverse a string. Python treats strings as a list of characters, so you can use list slicing to reverse strings.
8. Quickly transpose a matrix using zip. Zip takes two equal-length collections and merges them together in pairs.
9. You can multiply strings with integers.
As you can see, the string is repeated 4 times.
10. Python provides with block to work with resources that need to be free after you finish working with them. For example like a file.
Here the with block makes sure that the file is closed when the control exits the block. This saves you from calling close on the file every time you open one.
Conclusion
Hope this article was helpful. Follow me for more cool and informative articles on python.