forCodingInterviews Flashcards
if there are duplicate elements x in a list, then what does a.remove(‘x’) remove?
the first occurrence of x
finding the intersection of two sets
result = s1.intersection(s2) s1 & s2
finding the union of two sets
resul = s1.union(s2) or s1 | s2
how to iterate over a set?
for val in set: print(val)
convert a set into a list
list(s)
set membership
if element in set
dict membership
id key in d
list membership
if element in list
what does a filter function return and what’s one way to make it usable
it returns a filter object and can convert into list using list(filter(function, iterable))
can you use a filter object with a set?
yes
how to create a list of tuples from a dictionary such that a tuple is (key, value)?
list(dict.items());
adding an element to a tuple
remmeber tuples are immutable so t2 = t1 + (newElement,) REMEMBER THE COMMA AT THE END. This is creating a new tuple since tuples are immutable.
inserting element at a particular location n in a tuple
t3 = t2[:n] + (‘a’,) + t2[n:]
removing an element froma particular location n in a tupel
t3 = t1[:n] + t1[n+1:]
what objects pass by reference?
all mutable objects, i.e. list, set and dict. Non mutable objects are passed by value so any changes to those args inside the function will not be reflected outside.
adding elements to a set
a.add(2)
whats the difference between b=a and b = a[:] where a is a list
b=a –> any changes to a will be reflected in b
b = a[:] –> creates a copy of a so changes in a will not be reflected
for nested lists use deepcop