Mahhos
Mahhos

Reputation: 101

Change multiple line for loop to Single Line For Loop

This is a way of appending to a list through for loop:

lst = [] 
for i in range(5):
    lst.append(i)

Though the below may look nicer and better:

lst = [i for i in range(5)]

I was trying to write the below code same as the second format, but I keep getting error. can anyone help?

filtered_list = []
for childList in source_list:
    filtered_childList = remove_emptyElements(childList)    
    if filtered_childList:   
         filtered_list.append(filtered_childList)

Upvotes: 2

Views: 789

Answers (1)

Oleksandr Dashkov
Oleksandr Dashkov

Reputation: 2848

Try this code:

# one liner as you asked:
filtered_list = [remove_emptyElements(l) for l in source_list if remove_emptyElements(l)]

# but I think that this will be better:
filtered_list = (remove_emptyElements(l) for l in source_list)
filtered_list = [l for l in filtered_list if l]

Update: To solve your issue from the comments you can use this code snippet:

sequences_result = []
for sequence in sequences:
    for itemset in sequence:
        itemset_result = []
        for item in itemset.split(","):
            itemset_result.append(item.strip())
        sequences_result.append(itemset_result)
print(sequences_result)

Upvotes: 2

Related Questions