Hello Pythonistas,
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Let’s get started
1. Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this insteadÂ
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
2. Create a single string from all element in list
Instead of Iterating each element over the list using for loop and appending each element to the string , you can do this instead
>>> python = ["Python", "Syntax" , "is", "elegantly"]
>>> python_string = ' '.join(python)
>>> print(python_string)
Python Syntax is elegantly
3. Merging two dictionaries
Use update( ) to combine two set of dictionaries
>>> a = {"name":"Python", "creator":"Guido"}
>>> b = {"age": 30, "gender" : None}
>>> a.update(b)
>>> print(a)
{'gender': None, 'age': 30, 'name': 'Python', 'creator': 'Guido'}
4. List comprehension to create specific list
Use List Comprehension instead of for loop on case where you want to create a list from a sequence with certain criteria
That you’re going to specify , For instance in example below we have created a list of odd numbers in just one line of code( one liner )
>>> odd = [x for x in range(20) if x%2 != 0]
>>> print(odd)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
5. Reversing a string in Python
You can easily reverse your string with just a bit of slicing as shown below
>>> quote = "doog si doG"
>>> print(quote[::-1])
God is good
6. Unpacking a Python List
Instead or reassigning each variable to index in a list , you do this at once by unpacking them as shown in the code below
>>> names = ['Melisa', 'Lisa', 'Peace']
>>> niece, friend, crush = names
>>> print('{} {} {}'.format(niece, friend, crush))
Melisa Lisa Peace
7. Iterating over two python list
You can actually Iterate over two list at once without using nested for loop as shown below
>>> books = ['mabala', 'money heist', 'GOT']
>>> pages = [200, 300, 600]
>>> for book ,page in zip(books, pages):
... print("{}--->{}".format(book, page))
...
mabala--->200
money heist--->300
GOT--->600
8. Using all or any in conditional statement
Instead of writing many if else statement for you logic you can actually do this using any and all keywords
>>> data = [True, True, False]
>>> if any(data):
... print("at least")
...
at least
>>> if not all(data):
... print("Thats right")
...
Thats right
9. Cumulative summing a sequence of numbers
Incase you want the cumulative sum of numbers to do some plotting , you can easily do this using numpy using its cumsum ( ) function
>>> import numpy as np
>>> factors = list(np.cumsum(range(0,20,3)))
>>> print(factors)
[0, 3, 9, 18, 30, 45, 63]
10. Adding Index to Iterables(list, tuples etc..)
Do this to automatically index your elements within an Iterable
>>> students = ['Immaculate', 'Prisca', 'Lizy']
>>> student_with_index = list(enumerate(students))
>>> print(student_with_index)
[(0, 'Immaculate'), (1, 'Prisca'), (2, 'Lizy')]
11. import this (Python design principles)
One you do this , You will be suprised by seeing Zen of Writing Python code pop up in front of you
import this ''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!'''
This is legit brother… congrate… it will help me by alot
Any suggestion on what else I should cover ?
Wooooooooooow! Great boy
Thanks brother .. which one did you find interesting the most ?
Thanks for this Brother it will help alot
Thanks @Seynation Together we stand