How to add elements to a sub list in Python?

[亡魂溺海] 提交于 2021-02-05 08:15:12

问题


Consider a list inside a list

list1 = ["element1","element2",["subelement1","subelement2"]]

subelement1 can be accessed by index [2][0]

print (list1[2][0])

But how can I insert elements at [2][x] position if only two parameters can be passed to insert function.

list.insert(index, element) 

Lets say i want to insert "subelement0" at [2],[0]. That makes the list :

list1 = ["element1","element2",["subelement0","subelement1","subelement2"]]

回答1:


Try to insert element to sublist as below:

list1[2].insert(0, 'subelement0') 
print(list1)
#  ['element1', 'element2', ['subelement0', 'subelement1', 'subelement2']]



回答2:


I would like to extend the answer posted by @Andersson. It would be nice to checking the type of the list element, then insert a new value.

def list_modify(element_to_add):
  list1 = ["element1", "element2", ["subelement1", "subelement2"]]
  for index, value in enumerate(list1):
      if isinstance(value, list):
          list1[index].insert(0, element_to_add)
  print(list1)
  #  ['element1', 'element2', ['subelement0', 'subelement1', 'subelement2']]
if __name__ == "__main__":
  list_modify('subelement0')


来源:https://stackoverflow.com/questions/53868198/how-to-add-elements-to-a-sub-list-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!