DEV Community

Billy Okeyo
Billy Okeyo

Posted on • Originally published at billyokeyo.codes on

5 Python Tricks And Tips

Hey there, in this article I'll show you some quick python tips and tricks which will make your life more easier and help you write better code in python.

Let's get started

1. Swapping Two Numbers

At times you might find yourself wanting to swap two numbers and you are thinking of a better way to put it 🤔, so here's how I prefer to do it...

x , y = 10, 20 #Assigning 10 to x and 20 to y

print (x, y)

#Output will be 10, 20

x, y = y, x #Swapping the values 

print (x, y)

#Output will be 20, 10 
Enter fullscreen mode Exit fullscreen mode

And that's how easy it is to swap two numbers

*2. How to Reverse a String *

Reversing a string is taking a string and printing it in the reverse order, let's see how that can be achieved.

The output will be in reverse order

myString = "PythonProgramming"

print (myString)

#Output will be PythonProgramming 

print (myString[::-1])

# Output will be gnimmargorPnohtyP 
Enter fullscreen mode Exit fullscreen mode

3. How To Create A Single String from a List

If you have a list of words and you want to join them to form one sentence you can do that easily by using the code below

myList = [”Python", ”Programming", "Is", ”Fun”]

print (myList)

#Output will be ['Python', 'Programming', 'Is', 'Fun']

print (””.join(myList))

#Output will be PythonProgrammingIsFun
Enter fullscreen mode Exit fullscreen mode

4. How To Print the File Path of Imported Module

If you ever worked with a module and you want to know it's path so that you can see it's structure, you can do that easily by running this code

import os

print (os)

#Output will be the path of your os module 
Enter fullscreen mode Exit fullscreen mode

5. How To Find The Most Frequent Value in a List

If you have a list if numbers and you want to find which number appears in the list most frequent, you can do that easily by using this code

numbers = [2, 5, 6, 3, 2, 7, 5, 2, 8, 2, 3]

print (max(set(numbers), key = numbers.count))

#Output will be 2
Enter fullscreen mode Exit fullscreen mode

That's all I had for this article, if you have other tips and tricks feel free to leave them in the comments section and I'll be glad to check them out...

See you in the next article

Latest comments (1)

Collapse
 
codeperfectplus profile image
Deepak Raj

Website to learn Python, Machine Learning and Data Science.

bit.ly/codeperfectplus