Click here to Skip to main content
15,745,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is my list:
l = [[1, 2, 3], [11, 12, 'b', 'b', 'b'],[21, 't', 223], [4, 5, 6], [7, 8, 9],'demo',12.5]

my expected output like this by eliminating string 'b' and 't' in list;
[[1, 2, 3], [11, 12,], [21, 223], [4, 5, 6], [7, 8, 9], 'demo', 12.5]

What I have tried:

for i in l:
    if type(i) == list:
        for j in i:
            if type(j) == str:

i got output like this;
[[1, 2, 3], [11, 12, 'b'], [21, 223], [4, 5, 6], [7, 8, 9], 'demo', 12.5]

there is one string "b" in list so i dont know to delete im stuck
Updated 12-Apr-22 23:58pm

What you would need to do is move that code into a function and make the function recursive - so if encounters a list it calls itself to process that list.
Thinking Recursively in Python – Real Python[^]
Share this answer
darshanbs-wq 13-Apr-22 5:47am    
Richard MacCutchan 13-Apr-22 6:00am    
It would still fail because of removing items during the iteration. See my Solution below.
The problem is that you are changing a list while you iterate over it, which means later indexes are wrong. You need to use a shallow copy of the list for the iteration:
for i in l:
    if type(i) == list:
        cop = i[:] # make a copy of the list for the iterator
        for j in cop:
            if type(j) == str:
                i.remove(j) # remove from the original
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900