Python tips

Advanced print options

# with sep parameter

str1 = 'pythonists'
str2 = ''

print(str1, str2, sep='@')

# with end paramerter
print('Ram', end=', ')
print('Shyam', end=', ')
print('Sita', end='.')


[email protected]
Ram, Shyam, Sita.

Break the sentences into words

string = 'Python Tips and Tricks For Beginners'

break_into_lst = string.split(' ')



['Python', 'Tips', 'and', 'Tricks', 'For', 'Beginners']

N times String

Many of you use for loop or while loop print the same string “n” times. But this tip code will help you do it in an easy way. Check out the below code example to know.

# N times Stringstr1 = "learn"str2 = "happy"print(str1* 3) # learnlearnlearnprint(str2* 2) # happyhappy

Creating a single string from elements of a list

We can simply create a single string from all the elements of a given list by using "." with the join() function inside the print statement with the list variable. So, by this, we can easily get the single string data format from the multiple data elements given in list format. Example: Output:

Python use of Enums

In Python, we can simply use the Enums to check the number of occurrences of a variable inside the given function where it first occurred. We just have to use the word with the function name inside the print statement with the "." operator to print the number of the first occurrence of that variable inside the function. Example: Output:

Printing path of the imported module

If we need to print the file directory or path for the Python modules we have imported in the programs, then we just have to use the module name inside the print statement simply, and the file directory will be printed in the output. Example: Looking at the following Python program: Output:

The Operator for Matrix Multiplication

PEP 465 and Python 3.5 introduced the dedicated infix operator for matrix multiplication @. You can implement it for your class with the methods matmul, rmatmul, and imatmul. This is how elegant the code for multiplying vectors or matrices looks like:

Obtain the Cartesian Product

The built-in module itertools provides many potentially useful classes. One of them is a product used to obtain the Cartesian product:

Obtain the Index of the Maximal (or Minimal) Element

Python doesn’t provide a routine to directly get the index of the maximal or minimal element in a list or tuple. Fortunately, there are (at least) two elegant ways to do so: If there are two or more elements with the maximal value, this approach returns the index of the last one: To get the index of the first occurrence, you need to change the previous statement slightly: The alternative way is probably more elegant: To find the index of the minimal element, use the function min instead of max.

Obtain Current Date and Time

Python has a built-in module datetime that is versatile in working with dates and times. One of its methods, .now(), returns the current date and time: