10 lesser-known facts about python

Photo by Dan Dennis on Unsplash
  1. 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”.
for loop with else

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.

list and tuple assignment

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 -

indentation for braces

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.

variable assignment

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.

value swap

In python, you can just do this,

a, b = b, a

6. You can return multiple values at the same time.

return multiple values

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.

String reversal

8. Quickly transpose a matrix using zip. Zip takes two equal-length collections and merges them together in pairs.

Transpose of a matrix

9. You can multiply strings with integers.

string multiplication

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.

with block

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.


Hope this article was helpful. Follow me for more cool and informative articles on python.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Allwin Raju

Allwin Raju

Python Developer | Django Developer | Python Enthusiast