is my code okay to execute “if a list has a certain word, remove the elements coming after that?”

Tags: ,



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?


def to_lowercase(target):
    lowerlist=[x.lower() for x in target];
    for i in range(len(target)):
        target[i]=lowerlist[i]

def remove_equipment(targetlist):
    wordtarget=''
    for x in targetlist:
        if x in targetword:
            index =targetlist.index(x)
            del targetlist[index:]

targetword=['equipment:','accompaniments:','garnish:']

to_lowercase(testlist);

remove_equipment(testlist);

I tested with test list below.

testlist= ['brioche','sandwich','bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']

So far, I haven’t seen any error.

Answer

It probably works, but some suggestions:

  1. 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.
  2. Convention is to use underscores to separate words in variable names: test_list instead of testlist
  3. Avoid looping through test_list multiple times. Currently, to_lowercase loops once, remove_equipment once, and targetlist.index(x) will also loop. See below for a simplified approach:
test_list = ['brioche','sandwich', 'bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']
target_word = ['equipment:','accompaniments:','garnish:']

# to store results
res = []

for word in test_list:
    # assumes you want only lowercase results
    word = word.lower()

    # add word to result list.
    # assumes that you want to keep words up to and including the target word.
    # e.g. [..., 'garnish:']
    res.append(word)
    
    if word in target_word:
        # break to end the for-loop since you don't want anything beyond this word
        break

print(res)
# prints ['brioche', 'sandwich', 'bread,', 'shrimp,', 'peeled,', 'tail', 'fan', 'attached,', 'butter', 'dill', 'shallot', 'equipment:']


Source: stackoverflow