My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Python Cheat Sheet for JavaScripters

Python Cheat Sheet for JavaScripters

Nico Braun's photo
Nico Braun
·Jul 21, 2019

Python has a lot in common with JavaScript. Functions are first class citizens and everything is an object. Here is a little cheat sheet, I created after a deepdive into JavaScript:

String Interpolation

foo = 'bar'
baz = f'foo, {foo}.'
print(baz)

# Output: foo, bar.

Splat operator / unpacking - (spread)

eatables = {
    'mango': '1$',
    'banana': '0.5$'
}

drinks = {
    'water': '0.3$',
    'wine': {
        'white': '2$',
        'red': '1.5$'
    }
}

keys = {
    *eatables,
    *drinks
}

menu = {
    **eatables,
    **drinks
}

print(keys)
print(menu)

# Output: {'wine', 'mango', 'banana', 'water'}
# Output: {'mango': '1$', 'banana': '0.5$', 'water': '0.3$', 'wine': {'white': '2$', 'red': '1.5$'}}

Anonymous function

double = lambda x: x * 2
print(double(2))

# Output: 4

Immediate invoked function expression

(lambda name: print(name))('foo')

# Output: foo

Callback

def take_five(callback):
    callback(5)

take_five(lambda x: print(x*x))

# Output: 25

Closure

def outer_function(text):
    (lambda : # inner function
        print(text)
    )() 

outer_function('bar')

# Output: bar

Currying

def multiplier_factory(factor):
    return lambda x: x*factor

doubler = multiplier_factory(2)
print(doubler(4))

# Output: 8

Map

items = [1, 2, 3, 4, 5]
map_obj = map(lambda x: x**2, items) # returns iterable object
print(list(map_obj)) # use list to iterate

# Output: [1, 4, 9, 16, 25]

Filter

negative_numbers = filter(lambda x: x < 0, range(-5, 5))
print(list(negative_numbers))

# Output: [-5, -4, -3, -2, -1]

Zip

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica", "Vicky")
x = zip(a, b)
print(tuple(x)) # Read with tuple

# Output: (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

List Comprehension

numbers = [1, 2, 3, 4]
list_comp = [n**2 for n in numbers if n%2 == 0 and n**n > 10] # defined by square brackets
print(list_comp)

# Output: [16]

With key value pairs

tuples = [('A','Good'),('C','Faulty'),('E','Pristine')]
something = [[key+' is '+val] for key, val in tuples if val != 'Faulty']
print(something)

# Output: [['A is Good'], ['E is Pristine']]

Indirect nested

words_list = [['foo', 'bar'], ['baz', 'impossibru!']]
merged = [word for words in words_list for word in words]
print(merged)

# Output: ['foo', 'bar', 'baz', 'impossibru!']

Direct and indirect nested madness

split_merged = [letr for split_word in [[letter for letter in word] for words in words_list for word in words] for letr in split_word]
print(split_merged)

# Output: ['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'z', 'i', 'm', 'p', 'o', 's', 's', 'i', 'b', 'r', 'u', '!']

Generator expression

iterator = (item for item in ['a', 'b', 'c']) # defined by round brackets
result = next(iterator)
result = next(iterator)
iterator.close()
print(result)

# Output: b

Async/Await

import asyncio

async def simple():
    print("count one")
    await asyncio.sleep(1)
    print("count two")

await simple()

# Output: count one
# Output: count two

with generator

@asyncio.coroutine
def my_gen():
    print('tick')
    yield from asyncio.sleep(1)
    print('tack')

await my_gen()

# Output: tick
# Output: tack

with gather

import time

async def count():
    print("count one")
    await asyncio.sleep(1)
    print("count four")

async def count_further():
    print("count two")
    await asyncio.sleep(1)
    print("count five")

async def count_even_further():
    print("count three")
    await asyncio.sleep(1)
    print("count six")

async def gather_example():
    await asyncio.gather(
        count(), 
        count_further(), 
        count_even_further()
    )


s = time.perf_counter()

await gather_example()

elapsed = time.perf_counter() - s
print(f"Script executed in {elapsed:0.2f} seconds.")

# Output: count one
# Output: count two
# Output: count three
# Output: count four
# Output: count five
# Output: count six
# Output: Script executed in 1.00 seconds.