2

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)
Mahhos
  • 101
  • 1
  • 1
  • 12
  • While it technically is simple enough to answer your question as is, it would be nice to know what you're trying to do and what your expected output is—that'd help. – cs95 Oct 02 '18 at 01:12

1 Answers1

2

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)
Oleksandr Dashkov
  • 2,249
  • 1
  • 15
  • 29
  • Version 2 is definitely better. It avoids the extra call to `remove_emptyElements` and technically speaking calling `remove_emptyElements` could have side effects that result in a different `filtered_list` when using the oneliner. – timgeb Oct 02 '18 at 01:21
  • @timgeb yes I agree with you. And I think that the lists comprehensions it's not the best solution for the current problem. – Oleksandr Dashkov Oct 02 '18 at 01:29
  • Thank you very much. It exactly works as it was intended. I've got trouble reverting below one line loof to multiple lines loof. here is the original code: sequences = [[[item.strip() for item in itemset.split(",")] for itemset in sequence] for sequence in sequences] Multiple line loof that I tried: for sequence in sequences: for itemset in sequence: for item in itemset.split(","): sequences.append(item.strip()) It does not work as the original one. Any idea? – Mahhos Oct 03 '18 at 13:42
  • @Mahhos I added an example – Oleksandr Dashkov Oct 04 '18 at 08:51