50 Python single line codes you should know

50 Python single line codes you should know


It's amazing that some specific tasks can always be done easily with Python. Some cumbersome tasks can be done in a single line of code using python. Here are 50 Python single line code examples I collected.

 

1. Letter shifting words: guess whether the number and frequency of letters are the same

from collections import Counter  
 
s1 = 'below'  
s2 = 'elbow'  

print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')

or we can also do this using the sorted() method like this.

print('anagram') if sorted(s1) == sorted(s2) else print('not an anagram')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2. Binary to decimal

decimal = int('1010', 2)  
print(decimal) #10
  • 1
  • 2

3. Convert to lowercase

"Hi my name is Allwin".lower() 
# 'hi my name is allwin'  

"Hi my name is Allwin".casefold()  
# 'hi my name is allwin'
  • 1
  • 2
  • 3
  • 4
  • 5

4. Convert to capital letters

"hi my name is Allwin".upper()  
# 'HI MY NAME IS ALLWIN'
  • 1
  • 2

5. Convert string to byte type

"convert string to bytes using encode method".encode()  
# b'convert string to bytes using encode method'
  • 1
  • 2

6. Copy files

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

7. Quick sort

qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])
  • 1

8. Sum of N consecutive numbers

sum(range(0, n+1))

This is not efficient and we can do the same using the below formula.

sum_n = n*(n+1)//2
  • 1
  • 2
  • 3
  • 4
  • 5

9. Assignment exchange

a,b = b,a
  • 1

10. Fibonacci series

lambda x: x if x<=1 else fib(x-1) + fib(x-2)]
  • 1

11. Merge nested lists into one list

[item for sublist in main_list for item in sublist]
  • 1

12. Run an HTTP service

python3 -m http.server 8000
  • 1

13. Reverse list

numbers[::-1]
  • 1

14. Find the factor of a number

import math; fact_5 = math.factorial(5)
  • 1

15. List parsing using "for" and "if"

even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]  
# [2, 4]
  • 1
  • 2

16. Get the longest string from the list

words = ['This', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
# 'words'
  • 1
  • 2
  • 3

17. List derivation

li = [num for num in range(0,100)]  
# this will create a list of numbers from 0 to 99
  • 1
  • 2

18. Set derivation

num_set = { num for num in range(0,100)}  
# this will create a set of numbers from 0 to 99
  • 1
  • 2

19. Dictionary derivation

dict_numbers = {x:x*x for x in range(1,5) }  
# {1: 1, 2: 4, 3: 9, 4: 16}
  • 1
  • 2

20. if-else

print("even") if 4%2==0 else print("odd")
  • 1

21. Infinite cycle

while 1:0
  • 1

22. Check data type

isinstance(2, int)  
isinstance("allwin", str)  
isinstance([3,4,1997], list)
  • 1
  • 2
  • 3

23. While cycle

a=5  
while a > 0: a = a - 1; print(a)
  • 1
  • 2

24. Use "print()" to write to the file

print("Hello, World!", file=open('file.txt', 'w'))
  • 1

25. Calculate the frequency of a character in the string

print("umbrella".count('l'))# 2
  • 1

26. Merge two lists

list1.extend(list2)# contents of list 2 will be added to the list1
  • 1

27. Merge two dictionaries

dict1.update(dict2)  
# contents of dictionary 2 will be added to the dictionary 1
  • 1
  • 2

28. Merge two sets

set1.update(set2)  
# contents of set2 will be copied to the set1
  • 1
  • 2

29. Timestamp

import time; print(time.time())
  • 1

30. Elements with the most occurrences

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  
most_frequent_element = max(set(test_list), key=test_list.count)  
# 4

However, this is not efficient and we can do the same using the collections module in a more efficient way like this.

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  
  
from collections import Counter  
print(Counter(numbers).most_common()[0][0])# 4
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

31. Nested list derivation

numbers = [[num] for num in range(10)]  
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
  • 1
  • 2

32. Octal to decimal

print(int('30', 8))   
# 24
  • 1
  • 2

33. Convert key value pairs to dictionaries

dict(name='allwin', age=23)
  • 1

34. Calculation of quotient and remainder

quotient, remainder = divmod(4,5)
  • 1

35. Remove duplicate elements from the list

list(set([4, 4, 5, 5, 6]))
  • 1

36. Sort the list in ascending order

First, let us sort the list using the sorted() method. The sorted method will **return the sorted list**.

sorted([5, 2, 9, 1])# [1, 2, 5, 9]

Next, let us sort this using the sort() method. The sort() method will sort the original list and not return anything.

li = [5, 2, 9, 1]  
li.sort()  
  
print(li)  
# 1, 2, 5, 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

37. Sort the list in descending order

sorted([5, 2, 9, 1], reverse=True)# [9, 5, 2, 1]
  • 1

38. Get a string of lowercase letters

import string; print(string.ascii_lowercase)  
# abcdefghijklmnopqrstuvwxyz
  • 1
  • 2

39. Get a string of uppercase letters

import string; print(string.ascii_uppercase)  
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • 1
  • 2

40. Get the number from 0 to 9 of string type

import string; print(string.digits)  
# 0123456789
  • 1
  • 2

41. Hexadecimal to decimal

print(int('da9', 16))  
# 3497
  • 1
  • 2

42. Human readable date and time

import time; print(time.ctime())  
# Thu Aug 13 20:16:23 2020
  • 1
  • 2

43. Convert the string type of the list element to integer

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

44. Press "key" to sort the dictionary

# d = {'five': 5, 'one': 1, 'four': 4, 'eight': 8}  
{key:d[key] for key in sorted(d.keys())}  
# {'eight': 8, 'five': 5, 'four': 4, 'one': 1}
  • 1
  • 2
  • 3

45. Sort dictionaries by value

# x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}  
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}  
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
  • 1
  • 2
  • 3

46. Rotation list

# li = [1,2,3,4,5]# right to left  
li[n:] + li[:n] # n is the no of rotations  
li[2:] + li[:2]  
[3, 4, 5, 1, 2]# left to right  
li[-n:] + li[:-n]  
li[-1:] + li[:-1]   
[5, 1, 2, 3, 4]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

47. Remove numbers from string

''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))  
# abcdeffgvcg
  • 1
  • 2

48. Transpose matrix

list(list(x) for x in zip(*old_list))  
# old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]  
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]
  • 1
  • 2
  • 3

49. Filter even numbers from the list

list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))  
# [2, 4, 6]
  • 1
  • 2

50. Unpacking

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

come from: https://blog.csdn.net/os373/article/details/121035063? spm=1000.2115.3001.5927#8_ n__ forty-eight

Posted on Fri, 29 Oct 2021 06:35:19 -0400 by lobo235