1

How to remove multiple items from nested list in python 3, without using a list comprehension? And at times Indexerror came how to handle that?

split_list =[["a","b","c"],["SUB","d","e",],["f","Billing"]]
rem_word = ['SUB', 'Billing', 'Independent', 'DR']
for sub_list in split_list:
  for sub_itm in sub_list:
    if sub_itm not in rem_word:
        print(sub_itm)

Output Comes like this:

 a
 b
 c
 d
 e
 f

Expected Output:

split_list =[["a","b","c"],["d","e",],["f"]]

3 Answers 3

2

You can use always use a list-comprehension. Get all the words to be removed in a separate list and try this :

>>> split_list =[["a","b","c"],["SUB","d","e",],["f","Billing"]]
>>> rem_word = ['SUB', 'Billing', 'Independent', 'DR']
>>> output = [[sub_itm for sub_itm in sub_list if sub_itm not in rem_word] for sub_list in split_list]
[['a', 'b', 'c'], ['d', 'e'], ['f']]

If you want to do it without list comprehension, you need to declare a vacant list to append each new sub-list and also a new vacant sub-list to append all new sub-items. Check this :

output2 = []
for sub_list in split_list:
    new_sub_list = []
    for sub_itm in sub_list:
        if sub_itm not in rem_word:
            new_sub_list.append(sub_itm)
    output2.append(new_sub_list)

It outputs the same :

[['a', 'b', 'c'], ['d', 'e'], ['f']]
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much but i want without list comprehension
@pycoderr if you print it without appending it to other lists, it's going to print then one by one.
0

You could simply use map and filter

split_list = [["a", "b", "c"], ["SUB", "d", "e", ], ["f", "Billing"]]
remove_list = ["SUB", "Billing", "INDEPENDENT", "DR"]
split_list = list(map(lambda x: list(filter(lambda i: i not in remove_list, x)), split_list))

print(split_list)

2 Comments

thank you so much but i want without list comprehension
@pycoderr: There is no list comprehension in that code. There are other constructs, such as a map, a filter, and lambda expressions. Please clarify just what you want or do not want.
0

[[x for x in z if x!='SUB'] for z in split_list]

keep in mind that it is a nested list. Treat x as the sub element and z as the element. Also keep in mind that the above code will delete all 'SUB'. just for deleting the first instance use remove.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.