Tips an Tricks Python

Tính Phạm
2 min readMar 15, 2020

--

#1. Swap 2 number

a = 10
b = 20
a,b = b,a
a ->20
b ->10

#2 List comprehension

evens = [x for x in range(20) if x%2 ==0]
print(evens)
evens -> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

#3 Map

numbers = [1, 2, 3, 4, 5]def square(n):
return n**2
listSquare= list(map(square,numbers))listSquare -> [2, 4, 6, 8, 10]

#4 Filter

number = [1,2,3,4,5,6,7,8,9,10]
def even(x):
return x%2 == 0
listEven = list(filter(even,number))
listEven ->[2, 4, 6, 8, 10]

#5 Reduce

from functools import reduce
numbers = [1, 2, 3, 4, 5]
def sum(x,y):
return x+y
sumList = reduce(sum,numbers)
sumList -> 15 #(((1+2)+3)+4)+5

#6 Sort

lst = [[2, 7], [7, 3], [3, 8], [8, 7], [9, 7], [4, 9]]lst.sort(key = lambda inner:inner[0])print(tps)#[[2, 7], [3, 8], [4, 9], [7, 3], [8, 7], [9, 7]]

#7 Argument unpacking

def mult(*args):
result = 1
for i in args:
result *= i
return result
mult(2, 3)
6
mult(2, 3, 4)
24

#8 Decompose a collection

x, y, z = ['a', 'b', 'c']print(x, y, z)
a b c
a,b = [["Python", "C#", "Java"],["Django","LOL","Spring"]]
print(a,b)
['Python', 'C#', 'Java'] ['Django', 'LOL', 'Spring']

#9 Set

A set is an unordered collection with no duplicate elements.

myword = "NanananaBatman"
set(myword){'N', 'm', 'n', 'B', 'a', 't'}
# first you can easily change set to list and other way aroundmylist = ["a", "b", "c", "c"]# let's make a set out of itmyset = set(mylist)# myset will be:
{'a', 'b', 'c'}
# and, it's already iterable so you can do:
for element in myset:
print(element)
# but you can also convert it to list again:
mynewlist = list(myset)
# and mynewlist will be:
['a', 'b', 'c']

#9 Enumerate

mylist = ['a', 'b', 'd', 'c', 'g', 'e']
for i, item in enumerate(mylist):
print(i, item)
# Will give:
0 a
1 b
2 d
3 c
4 g
5 e
# but, you can add a start for enumeration:for i, item in enumerate(mylist, 16):
print(i, item)
# and now you will get:16 a
17 b
18 d
19 c
20 g
21 e

--

--

Tính Phạm
Tính Phạm

Written by Tính Phạm

càng đơn giản càng tốt

No responses yet