15,666,925 members
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.remove(j)

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
Posted
Updated 12-Apr-22 23:58pm

## Solution 1

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[^]

darshanbs-wq 13-Apr-22 5:47am
thanks
Richard MacCutchan 13-Apr-22 6:00am
It would still fail because of removing items during the iteration. See my Solution below.

## Solution 2

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:
Python
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

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

Top Experts
Last 24hrsThis month
 OriginalGriff 100 Richard MacCutchan 35 Member 16004134 30 Mike Hankey 10 Wonde Tadesse 5
 OriginalGriff 420 Richard MacCutchan 55 CPallini 50 Andre Oosthuizen 40 JudyL_MD 35

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