Skip to content Skip to sidebar Skip to footer

Using Remove On Nested Lists

n=[['dgd','sd','gsg'],['fsdsdf','sds','sdf']] >>> n.remove('sd') if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an e

Solution 1:

n[0].remove('sd')

or

for i in n:
  try:
    i.remove('sd')
  except ValueError:
    pass

Solution 2:

When you have nested lists you need to index the top level list to get to the child lists, only then can you use list operations on the child lists. So you need something like:

n[0].remove('sd')

The code you have is trying to remove the string : 'sd' from a list that only contains two lists: ['dgd','sd','gsg'] and ['fsdsdf','sds','sdf'].

Simply calling n.remove('sd') would work on nest lists if Python performed automatic tree recursion on nested collections which it does not.

Post a Comment for "Using Remove On Nested Lists"