Python Flashcards
Filter a list
l = [“ab”, “a”, “c”]
Return items that have a length more than 1
list(filter(lambda x: len(x) > 1, l))
Use reduce on a List
from functions import reduce
reduce(lambda a, b: a + b, myList)
This will sum up all the numbers left to right.
reduce(lambda a, b: a if a > b else b, myList)
This will return the max value from list
Insert 5 into Index 0 in List
x = [1,2,3,4]
x.insert(0,5)
or
x[0:0] = 5
Get character length away from ‘a’
x = ‘f’
ord(x) - ord(‘a’)
Can use to build tuple of 26 letters and add count of letters for an anagram problem (can then compare tuples to see if they match and words are anagrams)
Separate word into list of characters
word = “hello”
chars = [*word]
Deque and Operations
from collections import deque
x = deque()
x.append()
x.appendleft()
x.pop()
x.popleft))
Create decoder with message and alphabet
import string
alpha = string.ascii_lowercase
decorder = dict(zip(msg, alpha))
Dictionary comprehension
d = {“a”: 1, “b”: 5, “c”: 10}
Return any key over 2
{k:v for k,v in d.items() if v > 2}
Check if number is int or float
(4/2).is_integer()
Sum up all dictionary values
sum(d.values())
Stack underflow
stack = []
stack[-1]
Create a list with x number of spots
l = [0] * x
Filter a list
Apply function to elements in list
a = [1,2,3,4]
list(map(lambda x: x + 1, a))
Apply function to elements in dict
d = {“x”: 1, “a”: 2, “c”: 3}
c = list(map(lambda x: x + 1, d.values()))
new_d = dict(zip(d.keys(), c))
What prints out:
nums = [1,2,3,4,5]
for i in range(0, len(nums)):
print(i)
0,1,2,3,4
What prints out:
nums = [1,2,3,4,5]
for i in range(0, len(nums) + 1):
print(i)
0,1,2,3,4,5
Set starting value of a number without using 0
x = float(“-inf”)
Create dict that won’t throw error when accessing key doesn’t exist
from collections import defaultdict
result = defaultdict(list)
Scope
Block of code where object remains relevant
local / global
*args vs **kwargs
*args = unnamed args passed a tuple
def func1(this, *args):
print(this)
print(args)
func1(1,2,3)
> 1, (2, 3)
**kwargs = keyword args passed as dict
def func2(**kwargs):
print(kwargs)
func2(this=1, that=2)
> {“this”: 1, “that”: 2)
Remove duplicates from a file and write to a second file
seen = set()
with open(file1, “r+”) as fromFile, open(file2, “w”) as toFile:
l = fromFile.readlines()
fromFile.seek(0)
fromFile.truncate()
for line in l:
if line in seen:
toFile.write(line)
else:
fromFile.write(line)
seen.add(line)
read() vs readline() vs readlines()
read(): returns entire file as str
readline(): returns a single line up to line break
readlines(): reads all lines into a list
Split a string into a list of lines
s = “This list\nThat list”
s.splitlines()