Search code examples
pythonlistinsertsublist

How to insert an item into a sublist if sublist is a certain length?


If sublist is 4 items, keep, if list is 3 items insert "Null" into the third place of the sublist. A for loop with a conditional "if" would do it, but it's pretty slow. Is there any faster method?

 lst = [['4','4','4','4'],['3','3','3'],['1','42','','4'],['1','2','3']]

 Desired_List = [['4','4','4','4'],['3','3','Null','3'],['1','42','5','4'],['1','2','Null','3']]

What I have, which doesn't work for some reason I don't understand:

Desired_List = []
for sublist in lst: 
   if len(sublist) == 3:
      Desired_List.extend(sublist.insert(3,"Null"))
   else:
      Desired_List.extend(sublist)

This is really slow as I'm doing this to a large list. Are there any faster methods?


Solution

  • if you already change lst consider just using it instead of creating a new list Desired_List, simply do:

    >>> for sublist in lst: 
    ...    if len(sublist) == 3:
    ...       sublist.insert(2,"Null")
    ... 
    >>> lst
    [['4', '4', '4', '4'], ['3', '3', 'Null', '3'], ['1', '42', '', '4'], ['1', '2', 'Null', '3']]