The Ultimate Cheat Sheet of Equivalents in Python and Javascript
The Ultimate Cheat Sheet of Equivalents in Python and Javascript
Conditional assignment value = 'ADULT' if age >= 18 else 'CHILD' value = age >= 18? 'ADULT': 'CHILD';
Joining lists of strings items = ['A', 'B', 'C'] items = ['A', 'B', 'C'];
text = ', '.join(items) # 'A, B, C' text = items.join(', '); // 'A, B, C'
try: try {
proceed() proceed();
except MyException as err: } catch (err) {
print('Sorry! {}'.format(err)) if (err instanceof MyException) {
finally: console.log('Sorry! ' + err);
print('Finishing') }
} finally {
console.log('Finishing');
}
Unpacking lists a = 1 a = 1;
b = 2 b = 2;
a, b = b, a # swap values [a, b] = [b, a]; // swap values
first, second, *the_rest = [1, 2, 3, 4] # Python 3.6 [first, second, ...the_rest] = [1, 2, 3, 4];
# first == 1, second == 2, the_rest == [3, 4] // first === 1, second === 2, the_rest === [3, 4]
Iteration for item in ['A', 'B', 'C']: for (let item of ['A', 'B', 'C']) {
print(item) console.log(item);
}
Iterate through each items = ['a', 'b', 'c', 'd'] items = ['a', 'b', 'c', 'd'];
element and its index for index, element in enumerate(items): items.forEach(function(element, index) {
print(f'{index}: {element};') console.log(`${index}: ${element};`);
});