# Python tricks 101, what every new programmer should know.

Python is more popular than ever and people are proving on a daily basis that Python is a very powerful and easy-to-pick-up language.

I’ve been coding in Python for a few years, the last 6 months professionally, and here’s some of the things I wish I knew when I first started out:

1. String manipulation
2. List comprehension
3. lambda & map()
4. if, elif and else condition one-liners
5. zip()

# # 1: String manipulation

Python is great at determinering what you want to do with a string using mathematical operator like + and * :

>>> my_string = "Hi Medium..!"
>>> print(my_string * 2)
Hi Medium..!Hi Medium..!>>> print(my_string + " I love Python" * 2)
Hi Medium..! I love Python I love Python

We can reverse a string easily as well, using [::-1] and this isn’t limited to strings!:

>>> print(my_string[::-1])
!..muideM iH>>> my_list = [1,2,3,4,5]
>>> print(my_list[::-1])
[5, 4, 3, 2, 1]

What about a list of words? We can make a Yoda-translator!:

>>> word_list = ["awesome", "is", "this"]
>>> print(' '.join(word_list[::-1]) + '!')
this is awesome!

Above we make use of the .join() method, joining all elements in the reversed list with ' ' (space) and adding on an exclamation point.

# # 2: List comprehensions

Oh boy, once I learned about these my whole world changed (not really, but close enough). This is a really powerful, intuitive and readable way for making quick operations on a list.

Let’s say we have a random function of squaring a number and adding 5:

>>> def stupid_func(x):
>>> return x**2 + 5

Now let’s say we want to apply this function to all odd numbers in a list, this is probably the way you would do if you don’t know of list comprehensions:

>>> my_list = [1, 2, 3, 4, 5]
>>> new_list = []
>>> for x in my_list:
>>> if x % 2 != 0:
>>> new_list.append(stupid_func(x))
>>> print(new_list)
[6, 14, 30]

But there’s an easier way!:

>>> my_list = [1, 2, 3, 4, 5]
>>> print([stupid_func(x) for x in my_list if x % 2 != 0])
[6, 14, 30]

List comprehensions works with the syntax [ expression for item in list ] and if you’re feeling fancy with an additional Boolean condition like the “odd” condition above: [ expression for item in list if conditional ] this is the exact same as:

>>> for item in list:
>>> if conditional:
>>> expression

Very cool! We can still do a bit better though, because we don’t really need that “stupid_func”:

>>> print([x ** 2 + 5 for x in my_list if x % 2 != 0])
[6, 14, 30]

Boom!

# # 3: Lambda & Map

## Lambda

Lambda is a bit weird, but like everything else on this list, it’s really powerful and quite intuitive once you catch on.

Basically a Lambda function is a small, anonymous function. Why anonymous? Simply because Lambdas are most often used to perform small / simple operations which don’t require a formal function definition like def my_function() .

Let’s take the example above of squaring a number and adding 5. Above we made a formal function definition with def stupid_func(x) , now let’s recreate it with a lambda function:

>>> stupid_func = (lambda x : x ** 2 + 5)
>>> print([stupid_func(1), stupid_func(3), stupid_func(5)])
[6, 14, 30]

So why bother using this weird syntax? Well this becomes useful when you want to performe some simple operation without defining an actual function. Take the case of a list of number, how do we sort such a list in Python? One way is to use the sorted() method:

>>> my_list = [2, 1, 0, -1, -2]
>>> print(sorted(my_list))
[-2, -1, 0, 1, 2]

That did the trick, but let’s say we want to sort by the lowest squared number, we can use a lambda function to define the key, which is what the sorted() method uses to determine how to sort.

>>> print(sorted(my_list, key = lambda x : x ** 2))
[0, -1, 1, -2, 2]

## Map

Map is simply a function used to apply a function to some sequence of elements like a list. Let’s say we have to list where we want to multiply each element in one list with the corresponding element in the other, how do we do this? Using a lambda function and map!:

>>> print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6])))
[4, 10, 18]

This is simple and elegant compared to this monstrocity:

>>> x, y = [1, 2, 3], [4, 5, 6]
>>> z = []
>>> for i in range(len(x)):
>>> z.append(x[i] * y[i])
>>> print(z)
[4, 10, 18]

# # 4: if, elif and else condition one-liners

Somewhere in your code you’ll probably have something like:

>>> x = int(input())
>>> if x >= 10:
>>> print("Horse")
>>> elif 1 < x < 10:
>>> print("Duck")
>>> else:
>>> print("Baguette")

When you run this you’re prompted an input from the input() function, let’s say we enter 5, we’ll get Duck . But we can also write the whole thing in a one-liner like this:

print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")

It’s really that easy! Going through your old code you’ll find tons of places where a simple conditional if / else statement can be simplified to a one-liner.

# # 5: zip()

Remember the example from the “map()” section about applying something in parallel between two lists? zip() makes this even easier.

Lets say we have two lists, one containing first-names and one containing last-names, how do we merge these in an orderly fashion? Using zip()!:

>>> first_names = ["Peter", "Christian", "Klaus"]
>>> last_names = ["Jensen", "Smith", "Nistrup"]
>>> print([' '.join(x) for x in zip(first_names, last_names)])
['Peter Jensen', 'Christian Smith', 'Klaus Nistrup']

Woops! Mistake where made, my name isn’t Peter Jensen.. But we know how to fix this easily!:

>>> print([' '.join(x) for x in zip(first_names, last_names[::-1])])
['Peter Nistrup', 'Christian Smith', 'Klaus Jensen']

# Closing thoughts

This was just a quick list I threw together to give you an impression on some of the great things that Python can do. Please leave any feedback you have and also if you want me to explain something specific or if you feel like I made a mistake!