Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Python Worksheet For Effective Coding

This document provides examples of using list and dictionary comprehensions in Python. It shows how to use comprehensions to multiply, take powers, reverse, filter, and traverse lists. It also demonstrates combining two lists into a dictionary, adding conditions, checking values, and merging lists with zip. Comprehensions provide a concise way to create new structures from existing iterables in Python.

Uploaded by

Nischal Maharjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Worksheet For Effective Coding

This document provides examples of using list and dictionary comprehensions in Python. It shows how to use comprehensions to multiply, take powers, reverse, filter, and traverse lists. It also demonstrates combining two lists into a dictionary, adding conditions, checking values, and merging lists with zip. Comprehensions provide a concise way to create new structures from existing iterables in Python.

Uploaded by

Nischal Maharjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

[ Python List Comprehension ]

by Alex Kelin

prompt command result

**entity could be
variable = [***result*** for element in entity if
Concept range(), list, any
condition]
iterable value…

Multiply each lib = [4,8,2,4,0,3] >>> print(double_nums)


number double_nums = [num * 2 for num in lib] [8, 16, 4, 8, 0, 6]

lib = [4,8,2,4,0,3] >>> print(pow_nums)


POW each number
pow_nums = [pow (x, 2) for x in lib] [16, 64, 4, 16, 0, 9]

one = ['a', 'b', 'c', 'd', 'e'] >>> print(two)


two = one[::-1] ['e', 'd', 'c', 'b', ‘a']
Reverse a list
or >>> print(three)
three = ['a', 'b', 'c', 'd', 'e'][::-1] ['e', 'd', 'c', 'b', 'a']

one = ['a', 'b', 'c', 'd', 'e', 'f', ‘g']


result = one[2:6:2] >>> print(result)
Traverse a list
or ['c', ‘e']
result = [x for x in one[2:6:2]]

names = [‘Bob’, ‘Mike’, ‘John’]


>>> print(new_list)
Operations with new_list = [“Hi, ” + name for name in names]
['Hi, Bob', 'Hi, Mike',
strings or
'Hi, John']
new_list = [f ’Hi, {name}’ for name in names]

String call of the names = [‘Bob’, ‘Mike’, ‘John’, ‘Jerry’] >>> print(new_list)
first char new_list = [ x[0] for x in names] ['B', 'M', 'J', ‘J’]

names = [‘Bob’, ‘Mike’, ‘John’, ‘Jerry’] >>> print(lengths)


Length of a string
lengths = [ len(x) for x in names] [3, 4, 4, 5]

values = [‘h',1,'b','b',4,'1','a',4] >>> print(option_1)


[1, 'h', 4, 'a', 'b',
option_1 = list({x for x in values})
‘1’]
or >>> print(option_2)
option_2 = list(set(values)) [1, 'h', 4, 'a', 'b',
or ‘1’]
Unique values only
option_3 = [x for x in set(values)] >>> print(option_3)
[1, 'h', 4, 'a', 'b',
or
‘1']
option_4 = [] >>> print(option_4)
[option_4.append(x) for x in values if x not in ['h', 1, 'b', 4, '1',
option_4] 'a']

one = ['a', 1, 'b', 'b', 4, '1']


>>> print(common)
Common values two = ['h', 'l', 1, 'a', 'j', '1']
['a', 1, '1']
common = [x for x in one if x in two]

a = [5,1,6]
b = [3,2,4]
>>> print(united)
Unite two lists united = [ x for y in [a, b] for x in y]
[5, 1, 6, 3, 2, 4]
or
united = [x for x in a + b]
one = ['Jack', 'Brit', 'Lucas', 'Ben']
two = [10, 15, 4, 6] >>> print(nl)
Create nested list nl = [[name, age] for name, age in zip(one, two)] [['Jack', 10], ['Brit',
15], ['Lucas', 4],
or ['Ben', 6]]
nl = [[one[i], two[i]] for i in range(len(one))]

nl = [[4, 8], [15, 2], [23, 42]]


sum = [x + y for x, y in nl] >>> print(sum)
Nested list sum
or [12, 31, 65]
sum = [x + y for (x, y) in nl]

nl = [[4, 8], [15, 2], [23, 42]]


check = [x > y for x, y in nl] >>> print(check)
Nested list check
or [False, True, False]
check = [x > y for (x, y) in nl]

a = [5, 1, 6]
Sum integers two >>> print(new)
b = [3, 2, 4]
lists [8, 3, 10]
new = [x + y for x, y in zip(a, b)]

Conditional
one = [1, 2, 3, 4, 5, 6, 7] >>> print(new)
comprehension I,
new = [x if x % 2 == 0 else x * 2 for x in one] [2, 2, 6, 4, 10, 6, 14]
ternery operator

Conditional a = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print(b)


comprehension II b = [x for x in a if x > 5 and x % 2 == 0] [6, 8]

sent = 'it is I, Kai, Jack, and Brit'


Multiple Condition >>> print(c)
c = [x for x in sent.split() if x[0].isupper() and
comprehension I [‘Brit']
len(x) > 1 if ',' not in x]

all_clients = [{'name': 'Jack', 'age': 10,


'balance': 100}, {'name': 'Brit', 'age': 15,
'balance': 200}, {'name': 'Lucas', 'age': 4,
Multiple Condition >>> print(checked)
'balance': 300}, {'name': 'Ben', 'age': 6,
comprehension II 'balance': 400}] ['Lucas', 'Ben']
checked = [x['name'] for x in all_clients if
x['balance'] >= 300 or x['age'] > 20]

booleans = [True, False, True] >>> print(result)


Opposite boolean
result = [not x for x in booleans] [False, True, False]

>>> print(check)
names = ['Bob', 'Mike', 'John', 'Jerry']
Check for value I [False, False, True,
check = [x == 'John' for x in names]
False]

lib = [4, 8, 2, 4] >>> print(check)


Check for value II
check = [x > 3 for x in lib] [True, True, False, True]

names = ['Bob', 'Mike', 'John', 'Jerry', 'John']


Search for value >>> print(check)
check = [i for i, x in enumerate(names) if x ==
index [2, 4]
'John']
{ Python : Dictionary Comprehension }
by Alex Kelin

prompt command result

dictionary = { key: value for vars in iterable While comprehension


Concept if condition} len(keys)=len(values)

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 range(len(one))]) {1: 'a', 2: 'b', 3:
or 'c', 4: 'd', 5: 'e'}
hm = {one[i]: two[i] for i in range(len(one))}

one = [1, 2, 3, 4, 5]
two = ['a', 'b', 'c', 'd', 'e']
>>> print(hm)
Merge two lists hm = {key: value for (key, value) in zip(one, two)}
with zip() or {1: 'a', 2: 'b', 3:
'c', 4: 'd', 5: 'e'}
hm = dict(zip(one, two))
or
hm = {a: b for a, b in zip(one, two)}

>>> print(united)
one = {1: 'a', 2: 'b', 3: 'c'} {1: 'a', 2: 'b', 3:
two = {4: 'd', 5: 'e', 6: 'f'} 'c', 4: 'd', 5: 'e',
6: ‘f'}
united = {**one, **two} >>> print(one)
or {1: 'a', 2: 'b', 3:
Merge dicts
one.update(two) 'c', 4: 'd', 5: 'e',
6: ‘f’}
or
>>> print(united)
one.update(two)
{1: 'a', 2: 'b', 3:
united = one 'c', 4: 'd', 5: 'e',
6: ‘f’}

one = {1: 'a', 2: 'b', 3: 'c'}


one[4] = 'd' >>> print(one)
Add values one[5] = 'e' {1: 'a', 2: 'b', 3:
one[6] = ‘f' 'c', 4: 'd', 5: 'e',
6: ‘f'}
or
one.update({4: 'd', 5: 'e', 6: 'f'})

old_stock = {'water': 1.42, 'cheese': 2.5, 'milk':


2.0} >>> print(correction)
Moderate dict price = 0.76 {'water': 1.0792,
'cheese': 1.9, 'milk':
correction = {item: value*price for (item, value) in 1.52}
old_stock.items()}

one = [4, 1, 2, 2, 3, 1]
two = ['a', 'a', 'c', 'c', 'e']
>>> print(result)
Unique values only new_two = []
(order preserved) {4: 'a', 1: 'c', 2:
uv = [new_two.append(i) for i in two if i not in 'e'}
new_two]
result = {i: j for i, j in zip(one, new_two)}

one = [4, 1, 2, 2, 3, 1] >>> print(result)


Unique values only
(order not two = ['a', 'a', 'c', 'c', 'e'] {4: 'c', 1: 'e', 2:
preserved) 'a'}
result = {i: j for i, j in zip(one, set(two))}
a = [1, 2, 3, 4, 5] >>> print(result)
Limited by values
length b = ['a', 'b', 'c'] {'a': 1, 'b': 2, 'c':
result = {k: v for k, v in zip(b, a[:len(b)])} 3}

names = {'mike': 10, 'jack': 32, 'rachel': 55}


Dict with multiple >>> print(new_dict)
conditions new_dict = {k: v for (k, v) in names.items() if v % 2 {'jack': 32}
== 0 if v > 20}

Conditional
comprehension I a = {'mike': 10, 'jack': 32, 'rachel': 55} >>> print(a)
new_dict = {k: v for (k, v) in a.items() if v % 2 == {'mike': 10, 'jack':
0} 32}

names = {'jack': 38, 'tina': 48, 'ron': 57, 'john': >>> print(new_dict)
Conditional 33} {'jack': 'young',
comprehension II, new_dict = {x: ('old' if y > 40 else ‘young') for (x, 'tina': 'old',
ternery operator y) in names.items()} ‘Ron': 'old', 'john':
'young'}

names = ['alice', 'bob', 'kate', 'kimber'] >>> print(view)


Conditional size = [1, 2, 3, 4, 5, 6, 7] {'Alice': ' 1 small',
comprehension III, view = {names[i].capitalize(): (f' {size[i]} nice' if 'Bob': ' 2 small',
ternery operator i >= 2 else f' {size[i]} small') for i in 'Kate': ' 3 nice',
range(len(names))} 'Kimber': ' 4 nice'}

>>> print(res)
{'a': {1: 'a', 2: 'a',
keys =['a', 'b', 'c', 'd'] 3: 'a'}, 'b': {1: 'b',
Nested dictionary
comprehension I values = [1, 2, 3] 2: 'b', 3: 'b'}, 'c':
res = {k1: {k2: k1 for k2 in values} for k1 in keys} {1: ‘c', 2: 'c', 3:
'c'}, 'd': {1: 'd', 2:
'd', 3: 'd'}}

keys =['a', 'b', 'c', 'd'] >>> print(res)


Nested dictionary {'a': [1, 2, 3], 'b':
comprehension II values = [1, 2, 3]
[1, 2, 3], 'c': [1, 2,
res = {k1: [x for x in values] for k1 in keys} 3], 'd': [1, 2, 3]}

>>> print(counted)
Find length of names = ['Alex', 'Tom', 'Johnson', 'Bi', 'Foobar'] {'alex': 4, 'tom': 3,
variable counted = {x.lower(): len(x) for x in names if x} 'johnson': 7, 'bi': 2,
'foobar': 6}
Python lambda λ : functions
by Alex Kelin

prompt command result

function_name = ( lambda variable(s): result if Condition and ternery is


Concept
condition else result_2 ) optional

Simple value >>> print(squared(5))


squared = lambda x: x ** 2
operation 25

Multiple value >>> print(value(2,1))


value = lambda x, y: x + 2 - y
operation 3

check_num = (
>>> print(check_num(6))
Check single value lambda x: f'{x} is greater than 5' if x > 5
6 is greater than 5
else f'{x} is not greater than 5')

check_num = (
>>> print(check_num(2,3))
Check multiple lambda x, y: f'{x} and {y} are greater than 5' if
2 and 3 are not greater than
values x > 5 and y > 5
5
else f'{x} and {y} are not greater than 5')

lib = ['a', 'b', 'c', 'd'] >>> print(boolean)


Check for value
boolean = list(map(lambda x: x == 'b', lib)) [False, True, False, False]

lst = [1, 2, 3, 4, 5] >>> print(check_1)


Any() or all() check_1 = any(map(lambda x: x % 2 == 0, lst)) True
value check check_2 = all(map(lambda x: x % 2 == 0, lst)) >>> print(check_2)
False

>>> print(a)
[<function
lib = [3, 1, 2]
<listcomp>.<lambda> at
a = [lambda x=_: x + 1 for _ in lib]
0x104761a80>, ……]
b = [(lambda x: x * 2)(_()) for _ in a]
>>> print(b)
[8, 4, 6]

>>> print(c)
lib = [3, 1, 2, 4]
Operations with [3, 1, 2, 4]
c = list(map(lambda x: x, lib))
list >>> print(d)
d = list(map(lambda x: x / 2, lib))
[1.5, 0.5, 1.0, 2.0]

>>> print(e)
lib = ['Bob', 'Mike', 'John', 'Jerry']
[' Hi, Bob', ' Hi, Mike', ' Hi,
e = list(map(lambda x: f' Hi, {x}', lib))
John', ' Hi, Jerry']

lib_1 = ['a', 'b', 'c', 'd']


>>> print(f)
lib_2 = [20, 'M', 'T', 'V']
['a - 20', 'b - M', 'c - T', 'd - V']
f = list(map(lambda x, y: f'{x} - {y}', lib_1, lib_2))

a = ['a', 'b', 'c'] >>> print(new_dict)


Operations with
b = [1, 2, 3]
dict {'a': 2, 'b': 3, 'c': 4}
new_dict = dict(zip(a, map(lambda x: x+1, b)))

Determine length names = ['Bob', 'Mike', 'John', 'Jerry'] >>> print(lengths)


of a string lengths = [len(x) for x in names] [3, 4, 4, 5]

booleans = [True, False, True] >>> print(result)


Opposite boolean
result = [not x for x in booleans] [False, True, False]

Extract positive my_list = [1, -2, 3, -4, 5] >>> print(pos_nums)


values pos_nums = list(filter(lambda x: x > 0, my_list)) [1, 3, 5]

You might also like