Python tricks 101: Every new Programmer Should Know

Python tricks 101: 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. In this post, you'll learn Python tricks 101 for your projects

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.

1: String manipulation

Pun definitely intended

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: Lambda & Map

Crazy paint skills coming in from the right

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]

3: List comprehensions

<img src="https://miro.medium.com/max/1920/0aLxluAYQy7mgIvS3.jpg">

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 x2 + 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]

4: if, elif and else condition one-liners

<img src="https://miro.medium.com/max/640/08WuSDfscbkTHZPIL.jpg">

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']

Conclusion:

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!

Thanks for reading. Hopefully, you found this useful!

Learn more...

Python Tutorial for Absolute Beginners - Learn Python in 2019

☞ Complete Python Masterclass

☞ Python Programming Tutorial | Full Python Course for Beginners 2019 👍

☞ Top 10 Python Frameworks for Web Development In 2019

☞ Python for Financial Analysis and Algorithmic Trading

☞ Building A Concurrent Web Scraper With Python and Selenium

Originally published on towardsdatascience.com

python web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Hire Python Developers India

Looking to build robust, scalable, and dynamic responsive websites and applications in Python? At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, we constantly endeavor to give you exactly what you need. If you need to...

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...