DEV Community

Cover image for Python tips and tricks
Abdulmumin yaqeen
Abdulmumin yaqeen

Posted on • Edited on • Originally published at yaqeen.me

Python tips and tricks

Python is a popular and widely adopted programming language. In this article, we'll explore some tips and tricks to improve your code and get the most out of Python. Specifically for beginners, these tips will help you write cleaner, more effective code, also helping you get more done with less. Let's dive in!

1. list comprehension

let say you want to write a code that let say return a list of squares of numbers. the normal way of doing is:

squares = []
for i in range(1,100):
    squares.append(i*i)
Enter fullscreen mode Exit fullscreen mode

but list comprehension makes it easier to generate a new list based on an existing sequences or iterable.

syntax > [expression for item in iterable]

Here, expression is the value to be included in the new list, item is the element of the iterable being processed

Example

squares = [i*i for i in range(1,100)]
Enter fullscreen mode Exit fullscreen mode

2. lambda

lambda allows you create functions on the fly, allows you to also turn anything in to a function. lambda functions are also called anonymous functions.

add_ = lambda x, y: x+y
add_(5,7)
Enter fullscreen mode Exit fullscreen mode

Lambda functions are often used as a convenient way to define a function in one line of code. Lambda functions can take up any number of arguments, but are only limited by only one expression.

Here's an example of using a lambda function with the map() function to square each element of a list:

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)  # Output: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

lambda is really really powerful, but you would'nt appreciate it much if you are just starting out.

3. zip and unzip

you can use zip to combine two or more list together. Unlike extending a list with other lists, zip creates a tuple, where each tuple contains items from the corresponding indices of the two lists.

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
zipped = zip(names, ages)
list(zipped) # [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
Enter fullscreen mode Exit fullscreen mode

zip can also be in for loops

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(name, age)
Enter fullscreen mode Exit fullscreen mode

you can also use * to reverse do the reverse of zip

zipped = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
names, ages = zip(*zipped)# <<<<
names # ('Alice', 'Bob', 'Charlie')
ages # (25, 30, 35)
Enter fullscreen mode Exit fullscreen mode

4. f-strings

if you want to format a string in python with some other variables, the old way would be

"my names is {}".format(name)
Enter fullscreen mode Exit fullscreen mode

But, this method can get really messy. The f-string adresses this issue with a more cleaner and easier way.

f"my name is {name}"
Enter fullscreen mode Exit fullscreen mode

all you need is to add an f at the beginnig of the string and use curly braces {} to add anything from variables, arithmetics or even function calls

5 .join, .get functions

if you have a list of strings and you want to concatinate all of it with a separator in between, it is much more easier to use the .join method.

names = ['Alice', 'Bob', 'Charlie']
print(''.join(names)) #AliceBobCharlie
print(' '.join(names)) #Alice Bob Charlie
print(','.join(names)) #Alice,Bob,Charlie
print('*'.join(names)) #Alice*Bob*Charlie
Enter fullscreen mode Exit fullscreen mode

Additionally, instead of the traditional way of getting a value from a dictionary, it is much more efficient to use the get method.

students = {'Alice':'Economics', 'Bob':'Physics', 'Charlie':'Math'}

students['John'] # return KeyError
students.get('John') # return None
Enter fullscreen mode Exit fullscreen mode

you can also set a default value, which will be returned instead if the key is not found in the dictionary

students.get('John', 'Not Found') # returns Not Found
Enter fullscreen mode Exit fullscreen mode

Conclusion

These tips will definitely help out alot, even if you don't use them yourself, you would probably come across it in someone else's code. Hence, makes it easier for you to understand what happening.

Happy Coding!

Top comments (2)

Collapse
 
msshahid profile image
Shahid

Thanks for sharing !
It was helpful 🤗

Collapse
 
abdulmuminyqn profile image
Abdulmumin yaqeen

Glad to hear 💙