DEV Community

loading...

10 Useful Python One-Liners You Should Know

RebelX
The Rebel NeXtdoor | Python Developer | Developer Advocate | Ehub247, TechO’clock and iDer Ambassador | Technical Writer
・3 min read

The day I wrote my first line of code in Python, I become fascinated with the simplicity, popularity, and its famous one-liners. In this post, I want to present some python one-liners.
1. Swapping Two Variables

# a = 4 b = 5
a,b = b,a
# print(a,b) >> 5,4

Enter fullscreen mode Exit fullscreen mode

Let’s start with a simpler one by swapping two variables with each other. This method is one of the most simple and intuitive methods that you can write with no need to use a temp variable or apply arithmetic operations.

2. Multiple Variable Assignments

a,b,c = 4,5.5,'Hello'
#print(a,b,c) >> 4,5.5,hello

Enter fullscreen mode Exit fullscreen mode

You can use commas and variables to assign multiple values to the variables at a time. Using this technique, you can assign multiple data types var at a time. You can use a list to assign values to variables. Below is an example of assigning multiple values to different var from a list.

a,b,*c = [1,2,3,4,5]
print(a,b,c)
> 1 2 [3,4,5]

Enter fullscreen mode Exit fullscreen mode

3. Sum of Even Numbers In a List
There can be many ways of doing this, but the best and simplest way is to use the list indexing and sum function.

a = [1,2,3,4,5,6]
s = sum([num for num in a if num%2 == 0])
print(s)
>> 12

Enter fullscreen mode Exit fullscreen mode

4. Deleting Multiple Elements from a List
del is a keyword used in python to remove values from a list.

#### Deleting all even
a = [1,2,3,4,5]
del a[1::2]
print(a)
>[1, 3, 5]

Enter fullscreen mode Exit fullscreen mode

5. Reading Files

lst = [line.strip() for line in open('data.txt')]
print(lst)

Enter fullscreen mode Exit fullscreen mode

Here we are using list comprehension. First, we are opening a text file, and using a for loop, we are reading line by line. In the end, using strip we are removing all the unnecessary space. There is one much simpler and shorter way of doing this using just the list function.

list(open('data.txt'))
##Using with with also close the file after use
with open("data.txt") as f: lst=[line.strip() for line in f]
print(lst)

Enter fullscreen mode Exit fullscreen mode

6. Writing data to file

with open("data.txt",'a',newline='\n') as f: f.write("Python is awsome")

Enter fullscreen mode Exit fullscreen mode

The above code will first create a file data.txt if not already there, and then it will write Python is awsome in the file.

7. Creating Lists

lst = [i for i in range(0,10)]
print(lst)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
or 
lst = list(range(0,10))
print(lst)

Enter fullscreen mode Exit fullscreen mode

We can also create a list of strings using the same method.

lst = [("Hello "+i) for i in ['Karl','Abhay','Zen']]
print(lst)
> ['Hello Karl', 'Hello Abhay', 'Hello Zen']

Enter fullscreen mode Exit fullscreen mode

8. Palindrome

A palindrome is a number or a string that looks the same when it gets reversed.

text = 'level'
ispalindrome = text == text[::-1]
ispalindrome
> True

Enter fullscreen mode Exit fullscreen mode

9. To Check The Existence of a number in a list

num = 5
if num in [1,2,3,4,5]:
     print('present')
> present

Enter fullscreen mode Exit fullscreen mode

10. Simulating Toss of a coin
It may be not that important, but it can be very useful whenever you need to generate some random choice from a given set of choices.

import random; random.choice(['Head',"Tail"])
> Head
Enter fullscreen mode Exit fullscreen mode

Discussion (3)

Collapse
lifelongthinker profile image
Sebastian

Thanks for your post.

As much as I love the versatility of Python, it really lacks in some respects.

No 2 is a good example. Yes, it works, but it's not very readable.

No 6 is a little disaster. I guess 'a' stands for "append" (create the file if it doesn't exist, otherwise add), but such code is not optimized for reading. It is optimized for writing, which in general is a bad choice. Same goes for No. 4 and 8.

I understand that it is tough creating a language that is concise and readable, but IMHO the designer(s) of Python made some bad choices here.

Collapse
achalpathak profile image
Achal Pathak • Edited

@lifelongthinker
Couldn't agree more.
Although No 2 and 8 are perfectly fine IMO and are often used at production level code.

Collapse
lifelongthinker profile image
Sebastian

Just to be clear, my criticism is directed towards Python. It is in no way meant to belittle the efforts of your post! Thank you, nice roundup! Keep them coming.