I’m trying to write a code to remove all the words coming after a certain word from a set of words as below. I tested out but since I’m quite new to python I’m not sure if this code might cause a problem.
Can anyone review this code and point any possible risk from using this code?
JavaScript
x
18
18
1
def to_lowercase(target):
2
lowerlist=[x.lower() for x in target];
3
for i in range(len(target)):
4
target[i]=lowerlist[i]
5
6
def remove_equipment(targetlist):
7
wordtarget=''
8
for x in targetlist:
9
if x in targetword:
10
index =targetlist.index(x)
11
del targetlist[index:]
12
13
targetword=['equipment:','accompaniments:','garnish:']
14
15
to_lowercase(testlist);
16
17
remove_equipment(testlist);
18
I tested with test list below.
JavaScript
1
2
1
testlist= ['brioche','sandwich','bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']
2
So far, I haven’t seen any error.
Advertisement
Answer
It probably works, but some suggestions:
- Store your intended results in a separate list instead of changing (mutating) the original
testlist
. This can be useful if you need to compare the lists before and after your changes. - Convention is to use underscores to separate words in variable names:
test_list
instead oftestlist
- Avoid looping through
test_list
multiple times. Currently,to_lowercase
loops once,remove_equipment
once, andtargetlist.index(x)
will also loop. See below for a simplified approach:
JavaScript
1
22
22
1
test_list = ['brioche','sandwich', 'bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']
2
target_word = ['equipment:','accompaniments:','garnish:']
3
4
# to store results
5
res = []
6
7
for word in test_list:
8
# assumes you want only lowercase results
9
word = word.lower()
10
11
# add word to result list.
12
# assumes that you want to keep words up to and including the target word.
13
# e.g. [..., 'garnish:']
14
res.append(word)
15
16
if word in target_word:
17
# break to end the for-loop since you don't want anything beyond this word
18
break
19
20
print(res)
21
# prints ['brioche', 'sandwich', 'bread,', 'shrimp,', 'peeled,', 'tail', 'fan', 'attached,', 'butter', 'dill', 'shallot', 'equipment:']
22