I have to write a function that takes a list(or string) and and object and returns the copy of the list up to but not including the first occurrence of that object, or all the elements if that object is not in the list.
I know i have to use loop here but what I'm confused at is list and strings use different methods for finding the index of that object. How can I use that with the loops to get my function up to the first occurrence of that object.
def up_to_first(item, element):
if type(item) == list:
index_of_element = item.index(element)
res = [ ]
for i in range(0, index_of_element):
sliced_list = item[0 : index_of_element]
Try the following function:
def up_to_first(seq, obj): if obj not in seq: return seq return seq[:seq.index(obj)]
This will return the sequence
obj is not in that sequence, and will return the sequence up to, but not including
obj otherwise. However, this function as it is will break if you are not careful about types. For example, it will work if you are looking for
[1, 2, 3, 4, 5] (and return
[1, 2, 3, 4]), but will raise an error if you look for
5 in a string.
>>> up_to_first([1, 2, 3], 3) [1, 2] >>> up_to_first('abcdef', 'd') 'abc' >>> up_to_first([1, 2, 3], 'a') [1, 2, 3] >>> up_to_first('abcdef', 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../.../test.py", line 2, in up_to_first if obj not in seq: TypeError: 'in <string>' requires string as left operand, not int