Modifying list contents in Python

list, python

Solution

for sublist in thelist:
  sublist.insert(0, 9)

don't use built-in names such as `list` for your own stuff, that's just a stupid accident in the making -- call YOUR stuff `mylist` or `thelist` or the like, not `list`.

Edit: as the OP aks how to insert > 1 item at the start of each sublist, let me point out that the most efficient way is by assignment of the multiple items to a slice of each sublist (most list mutators can be seen as readable alternatives to slice assignments;-), i.e.:

for sublist in thelist:
  sublist[0:0] = 8, 9

`sublist[0:0]` is the empty slice at the start of `sublist`, and by assigning items to it you're inserting the items at that very spot.

Problem

I have a list like: ``` list = [[1,2,3],[4,5,6],[7,8,9]] ``` I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like: ``` list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] ``` How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.

Original source