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