HomeArtificial IntelligenceArtificial Intelligence EducationPython tricks 101 that every new programmer should know.

Python tricks 101 that 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 tricks 101 that every new programmer should know. 1

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

Python tricks 101 that every new programmer should know. 2

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!

This article has been published from the source link without modifications to the text. Only the headline has been changed.

Most Popular