Python One Liners
Python One Liners
by Alex Kelin
>>> print(name,
Assigning multiple name, quantity, price = 'Book', 3, 4.99 quantity, price)
values to variables
Book 3 4.99
a = 1
Swapping two >>> print(a, b)
b = 2
variables 2 1
a, b = b, a
Conditional
one = [1, 2, 3, 4, 5, 6, 7] >>> print(new)
comprehension,
new = [x if x % 2 == 0 else x * 2 for x in one] [2, 2, 6, 4, 10, 6, 14]
ternery operator
>>> print(all(a))
a = [True, True, True] True
Check for False b = [True, True, False]
>>> print(all(b))
False
>>> print(a)
Printing elements a = [1, 2, ‘three', 4, 5] [1, 2, ‘three', 4, 5]
of a collection >>> print(*a)
1 2 three 4 5
>>> print(option_1)
[1, 'h', 4, 'a', 'b',
values = [‘h',1,'b','b',4,'1','a',4]
‘1’]
option_1 = list({x for x in values})
or >>> print(option_2)
option_2 = list(set(values)) [1, 'h', 4, 'a', 'b',
Unique values only or ‘1’]
[] option_3 = [x for x in set(values)] >>> print(option_3)
or [1, 'h', 4, 'a', 'b',
option_4 = [] ‘1']
[option_4.append(x) for x in values if x not in >>> print(option_4)
option_4]
['h', 1, 'b', 4, '1',
'a']
one = [1, 2, 3, 4, 5]
two = ['a', 'b', 'c', 'd', ‘e']
>>> print(hm)
Merge two lists hm = dict([(one[i], two[i]) for i in
into {:} {1: 'a', 2: 'b', 3: 'c',
range(len(one))]) 4: 'd', 5: 'e'}
or
hm = {one[i]: two[i] for i in range(len(one))}