How to add elements to a sub list in Python?

前端 未结 2 1189
挽巷
挽巷 2021-01-26 23:09

Consider a list inside a list

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

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

相关标签:
2条回答
  • 2021-01-26 23:22

    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')
    
    0 讨论(0)
  • 2021-01-26 23:29

    Try to insert element to sublist as below:

    list1[2].insert(0, 'subelement0') 
    print(list1)
    #  ['element1', 'element2', ['subelement0', 'subelement1', 'subelement2']]
    
    0 讨论(0)
提交回复
热议问题