Skip to content

Instantly share code, notes, and snippets.

View ChaitanyaBaweja's full-sized avatar

Chaitanya Baweja ChaitanyaBaweja

View GitHub Profile
list = [1, 2, 3, 4]
cube_list = []
for i in list:
cube_list.append(i**3)
print(cube_list) # Output: [1, 8, 27, 64]
old_list = [1, 2, 3, 4]
cube_list = [i**3 for i in old_list]
print(cube_list) # Output: [1, 8, 27, 64]
old_list = [1, 2, 3, 4]
new_list = []
for i in old_list:
if i%2 == 0:
new_list.append(i**3)
else:
new_list.append(i**2)
print(cube_list) # Output: [1, 8, 9, 64]
old_list = [1, 2, 3, 4]
new_list = [i**3 if i%2 == 0 else i**2 for i in old_list]
print(new_list) # Output: [1, 8, 9, 64]
a= [1,2,3,4]
b = [10,11]
cart_prod = []
for i in a:
for j in b:
cart_prod.append((i,j))
print cart_prod
# Output:
# [(1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11)]
a = [1,2,3,4]
b = [10, 11]
cart_prod = [(i,j) for i in a for j in b]
print cart_prod
# Output:
# [(1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11)]
a = [1,2,3,4,5,6]
b = [1,5,6]
common_list = [i for i in a if i in b]
print common_list
# Output:
# [1, 5, 6]
@ChaitanyaBaweja
ChaitanyaBaweja / apply.py
Created December 21, 2018 11:14
Applies function given by f to each element in L
def apply(L, f):
"""
Applies function given by f to each element in L
Parameters
----------
L : list containing the operands
f : the function
Returns
-------
result: resulting list
@ChaitanyaBaweja
ChaitanyaBaweja / apply_func.py
Last active December 22, 2018 15:21
Applies function given by each element in L to x
from math import exp
def apply_func(L,x):
"""
Applies function given by each element in L to x
Parameters
----------
L : list containing the operations
x : the operand
Returns
@ChaitanyaBaweja
ChaitanyaBaweja / printer.py
Last active December 22, 2018 15:50
A class that whenever called, prints whatever it stores.
class Printer:
def __init__(self, s):
self.string = s
def __call__(self):
print(self.string)