Skip to content

Instantly share code, notes, and snippets.

@elfosardo
Created July 28, 2020 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elfosardo/693d8edecb779656314fa07bde395ac7 to your computer and use it in GitHub Desktop.
Save elfosardo/693d8edecb779656314fa07bde395ac7 to your computer and use it in GitHub Desktop.
Python one-liners
### Swapping the value of variables
# a->b
# b->a
a, b = b, a
# Works with more values
a, b, c, d = d, c, b, a
### List comprehension
# instead of:
ls = []
for i in range(5):
ls.append(i)
# do:
ls = [i for i in range(5)]
### map
# executes a function for every element in a list
ls = list(map(int, ["1", "2", "3"]))
#ls = [1, 2, 3]
### filter
# checks iterables, for example, the elements of a list and removes
# the elements that return False (do not meet the criteria)
ls1 = [1, 3, 5, 7, 9]
ls2 = [0, 1, 2, 3, 4]
common = list(filter(lambda x: x in ls1, ls2))
#common = [1, 3]
### reduce
# apply a function to every element until only one element is left
from functools import reduce
print(reduce(lambda x, y: x*y, [1, 2, 3]))
#print 6
### lambda
# substitute a regular function
fullName = lambda first, last: f"{first} {last}"
name = fullName("Tom", "Walker") #name = Tom Walker
### reverse
ls = [1, 2, 3]
ls.reverse()
#ls = [3, 2, 1]
### print same element multiple times using *
print("x"*5)
#print xxxxx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment