Browsed by
Category: Python

Python tips and tricks

Python tips and tricks

According to Stack Overflow, Python is the fastest growing programming language. Netflix uses Python, IBM uses Python, and hundreds of other companies all use Python. Let’s not forget Dropbox. Dropbox is also created in Python.

Some of the advantages Python offers when compared to other programming languages are:

  • Compatible with major platforms and operating systems
  • Many open-source frameworks and tools
  • Readable and maintainable code
  • Robust standard library
  • Standard test-driven development

Lets look at some cool tips and tricks in python

Concatenating Strings

When you need to concatenate a list of strings, you can do this using a for loop by adding each element one by one. However, this would be very inefficient, especially if the list is long. In Python, strings are immutable, and thus the left and right strings would have to be copied into the new string for every pair of concatenation.

A better approach is to use the join() function as shown below:

characters = ['p', 'y', 't', 'h', 'o', 'n']
word = "".join(characters)
print(word) # python

Using ZIP When Working with Lists

Suppose you were given a task to combine several lists with the same length and print out the result? Again, here is a more generic way to get the desired result by utilizing zip()as shown in the code below:

countries = ['France', 'Germany', 'Canada']
capitals = ['Paris', 'Berlin', 'Ottawa']
for country, capital in zip(countries,capitals):
    print(country, capital) # France Paris 
                              Germany Berlin
                              Canada Ottawa

Using itertools

The Python itertools module is a collection of tools for handling iterators. itertools has multiple tools for generating iterable sequences of input data. Here I will be using itertools.combinations() as an example. itertools.combinations() is used for building combinations. These are also the possible groupings of the input values.

Let’s take a real world example to make the above point clear.

Suppose there are four teams playing in a tournament. In the league stages every team plays against every other team. Your task is to generate all the possible teams that would compete against each other.

Let’s take a look at the code below:

import itertools
friends = ['Team 1', 'Team 2', 'Team 3', 'Team 4']
list(itertools.combinations(friends, r=2))
 # [('Team 1', 'Team 2'),      ('Team 1', 'Team 3'),  ('Team 1', 'Team 4'),  ('Team 2', 'Team 3'),  ('Team 2', 'Team 4'),  ('Team 3', 'Team 4')]

Convert Two Lists Into a Dictionary

Let’s say we have two lists, one list contains names of the students and second contains marks scored by them. Let’s see how we can convert those two lists into a single dictionary. Using the zip function, this can be done using the code below:

students = ["Peter", "Julia", "Alex"]
marks = [84, 65, 77]
dictionary = dict(zip(students, marks))
print(dictionary) # {'Peter': 84, 'Julia': 65, 'Alex': 77}

Return Multiple Values From a Function

Python has the ability to return multiple values from a function call, something missing from many other popular programming languages. In this case the return values should be a comma-separated list of values and Python then constructs a tuple and returns this to the caller. As an example see the code below:

def multiplication_division(num1, num2):
    return num1*num2, num1/num2
product, division = multiplication_division(15, 3)
print("Product=", product, "Quotient =", division) # Product= 45 Quotient = 5.0

Using sorted() Function

Sorting any sequence is very easy in Python using the built-in method sorted()which does all the hard work for you. sorted()sorts any sequence (list, tuple) and always returns a list with the elements in sorted manner. Let’s take an example to sort a list of numbers in ascending order.

sorted([3,5,2,1,4]) # [1, 2, 3, 4, 5]

Taking another example, let’s sort a list of strings in descending order.

sorted(['france', 'germany', 'canada', 'india', 'china'], reverse=True)

# ['india', 'germany', 'france', 'china', 'canada']
Iterate DataFrame in Python

Iterate DataFrame in Python

In recent time, data analytics is the most demanding area in IT. Panda is a library which is commonly used for analytic using Python programming language. In Panda, Series and DataFrame are the data structures that we commonly use and because of these data structures, Panda is so popular. In this article, we will be discussing different ways to iterate DataFrame.

Read More Read More

Sort dictionary in Python

Sort dictionary in Python

Python dictionary stores data in key-value pairs. In some situations, programmers need to sort the dictionary object as per their requirement which may be based on key or value. To sort dictionary object, you can user sorted() method and pass either keys or values from the dictionary which sorts the elements in their natural order. For example, if the elements are all integers, then smaller numbers go earlier in the list. If the elements are all strings, they are arranged in alphabetic order. Below examples demonstrate different ways to sort the dictionary based on key or value.

Read More Read More