15 Useful One Liners in Python that you should know

15 Useful One Liners in Python that you should know

Python is a widely-used general-purpose, high-level programming language. As it is easily readable and to code, programmers searching for concise and less code that saves time.

So here i am presenting very famous and easy to remember one liners in python:

1. Swap Objects

Suppose we to swap two numbers a and b, then one to swap number is

a = a+b;
b = a-b;
a = a-b;

But we can do in one line as

a,b = b,a

2. String Palindrome

This can be using list slicing method.

str == str[:: -1]
str.reverse()

3. Factorial Number

Using Lambda Function

fact = lamda n: [1,0] [n>1] or fact (n-1)*n
import math ; math.factorial(n)

4. Fibonacci Number

Using Lambda Function

fib = lambda n : n if n<=1 else fib(n-1) + fib(n-2)

5. List Comprehension

square = [x**2 for x in range(5)]

Square of number using lambda function

sqr = lambda x: x * x

6. Star Pattern of Right Angle Triangle

* 
* * 
* * * 
* * * * 
* * * * *
print('\n'.join('* ' * i for i in range(1, n + 1)))

7. Sum of Even Numbers In a List

Using 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)

8. Simulating Toss of a coin

Using random module

import random; random.choice(['Head',"Tail"])

9. Copy files

import shutil; shutil.copyfile('source.txt', 'dest.txt')

10. Combine nested lists to a single list

[item for sublist in main_list for item in sublist]

11. Run an HTTP server

python3 -m http.server 8000

12. Infinte while loop

while 1:0

13. Human readable DateTime

import time; print(time.ctime())

14. Hypotanuse

import math; math.hypot(8, 6)

15. Convert a list of strings to integers

list(map(int, ['1', '2', '3']))