Remove String Elements from Nested List

#python

Soham Kundu Mar 19 2021 · 1 min read
Share this

Hello, members

Let's get straight to the point 

Details of the question  one can find in 

Video Named - 4th March Live Class Python List Manipulation

Timestamp - 56:52-57:55

Basically the question was that

  • There is list of lists ,
  • Such that in the nested list there are string elements you need to print the index of those elements and then remove them
  • Finally we needed to print the 2nd element in that nested list
  • Issue ?

    The  issue lies in point number 2 the moment you try to simple pop()/remove() operations you will run into error. So in this article we will focus on that point particularly

    Because

  • When you do pop() the list size shrinks and the range of indexes is updated i.e for example (0,4) becomes(0,3) after 1 pop
  • This is what happens
  • If we have ['a',1,'b','b'] then our target indexes are 0,2,3 right, but after 1 pop() our target indexes will change to 1,2
  • So with that being said

    Simply using pop() will not get the job done, hence we go DIY mode

    So this is  the Algo I adopted

  • If l is the input list of lists of size N such that we have string elements in the nested lists
  • Thus our input list will look as follows
  • [ [1, 3], (5+6j), ['c', 'c', 1, 'c'], ['c', 4, 'c', 5, 6, 'c'], [4, 'S', 4, 'S'], [7, 'R', 7, 'R'], 10]
  • Create list note of size N^2 
  • Assuming each nested list will have at max N element thus in total we will have N^2 elements
  • In note we will simply 'note/map' the indexes of each string element inside the nested list
  • Thus for l = [ [1, 3], (5+6j), ['c', 'c', 1, 'c'], ['c', 4, 'c', 5, 6, 'c'], [4, 'S', 4, 'S'], [7, 'R', 7, 'R'], 10] 
  • note will look as follows pointing to the indices of string elements in nested list
  • [None, None, [0, 1, 3], [0, 2, 5], [1, 3], [1, 3], None, None, None, None]
  • Now for each element in list note that is not None 
  • We will iterate through note and pluck values from it to pop from list 
  • While poping if we have already popped once
  •  Then we will reduce the values obtained which is basically the index by the times we have popped to get the updated value hence the indexes
  • Thus the issue is solved that was giving us errors, if we used pop() simply
  • Please try it on your own first to understand the logic.

    I will post the code in Part - 2 so as to modularize the content.

    Till then,

    Namaste

    Comments
    Read next