Python Tricks and Tips that You Should?Know.

Python Tricks and Tips that You Should?Know.

When you start learning Python, it may take a while to pick up some tips and tricks that will make your programming life much easier. In this article, we are going to explore some tricks and tips that you can use in your code.

1. Printing horizontally

When looping through an iterable, the print function prints each item in the new line. This is because the print function has a parameter called end. By default, the end parameter has an escape character (end =’\n’). To print horizontally, we need to remove the escape character and replace it with an empty string (end = " "). Here is the code to demonstrate that:

No alt text provided for this image


2. Merging dictionaries

If you have two dictionaries that you want to combine, you can combine them using two easy methods. You can use the merge (|) operator or the (**) operator. Below, we have two dictionaries, a and b. We are going to use these two methods to combine the dictionaries. Here is the code below:

No alt text provided for this image

3. Flatten a nested?list?

If you have a nested list( [[1, 2,3],[4, 5,6]]) and you want to flatten it, you can use the chain class from the?itertools?module. See the code below:

No alt text provided for this image

4. Count occurrences of an item in a?list

If you have a list of items and you want to know how many times each item appears in the list, you can use the?counter class?from the collections module. Let’s say we want to know how many times the name ‘Peter’ appears in the list; here is how we can do it using the?counter class.

No alt text provided for this image

5?. Print?pretty

Let's say you have a dictionary and you want to print out the elements sorted alphabetically; you can use the?pprint?module. Here is the code to demonstrate that:

No alt text provided for this image

Conclusion

There you have it, tips and tricks that you may use in your code. If you are interested in taking your Python skills to another level, please check out this book below.

No alt text provided for this image


Omar Faruk

Software Engineer | Python, AI, Langchain, Langgraph, Django, FastAPI | API Development & Optimization | AWS & Docker Enthusiast

2 年

Which is faster between ' | ' and ' ** '???

回复

要查看或添加评论,请登录

Benjamin Bennett Alexander的更多文章

社区洞察

其他会员也浏览了