In this post, you'll see 5 Python tricks 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:
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 “
>>> print([x ** 2 + 5 for x in my_list if x % 2 != 0]) [6, 14, 30]
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
>>> 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 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]
Python is great at determinering what you want to do with a string using mathematical operator like
>>> 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.
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.
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
>>> 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']
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!
Learn Python for Machine Learning and Web Development. Can Python be used for machine learning? Python is widely considered as the preferred language for teaching and learning ML (Machine Learning). Can I use Python for web development? Python can be used to build server-side web applications. Why Python is suitable for machine learning? How Python is used in AI? What language is best for machine learning?
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...
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...
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.
How To Plot A Decision Boundary For Machine Learning Algorithms in Python, you will discover how to plot a decision surface for a classification machine learning algorithm.