Non-obvious possibilities of python syntax

Sergei
Sergei
Jul 2, 2018 · 4 min read

Hi! All of us (ok not all :)) know python as wide-used, simple-to-read, easy-to-start programming language.

But at the same time python syntax allows to make really strange things.

Rewrite multiline function with lambda

As it’s known python lambda doesn’t support multiline code. But it can be simulated.

Sounds strange but above function can be replaced with lambda-function:

Never do that in production code :)

Ternary operator

Modern python gives you simple intuitive syntax:

But it also can be rewritten via:

Btw, next variant is incorrect:

Remove repeated symbols via list comprehension

Let’s transform string x = 'tteesstt' to 'test'.

  1. compare a symbol with previous in original string:

2. save previous symbol in temporary variable:

3. compare a symbol with previous in new string:

4. via reduce & lambda:

Fibonacci via list comprehension

  1. save temporary values in list:

2. save temporary values in dict:

3. via reduce & lambda:

4. the quickest variant:

Eternal cycle with list comprehension

List slice tricks

  1. copy list:

2. remove/replace any number of elements:

3. add elements to begin of list:

4. add elements to end of list:

5. reverse list:

Replace method byte code

Python prohibits to replace instance method, making it as read-only property:

But it can be replaced on byte-code level:

Note! It has influence not only to current instance but to class (if to be precise to function which is bound with class) and all other instances too:

Mutable object as default function argument

To assign mutable object as default value to function argument is very dangerous and there are a lot of tricky questions on interviews about that. But it can be helpful as cache mechanism.

  1. Factorial:

2. Fibonacci:

Sergei

Written by

Sergei

Software Engineer. Senior Backend Developer at Pipedrive. PhD in Engineering. My interests are IT, High-Tech, coding, debugging, sport, active lifestyle.

Sergei

Written by

Sergei

Software Engineer. Senior Backend Developer at Pipedrive. PhD in Engineering. My interests are IT, High-Tech, coding, debugging, sport, active lifestyle.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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