Changing the contents of a list in Python

I have a list like:

list = [[1,2,3],[4,5,6],[7,8,9]]

I want to add a number at the beginning of each value in the list programmatically, let's say that it is 9. I want the new list to be as follows:

list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]]

How do I do this in Python? I know this is a very trivial question, but I could not find a way to do this.

+3
source share
5 answers
for sublist in thelist:
  sublist.insert(0, 9)

do not use built-in names, such as listfor your own things, which is just a stupid accident in the process of creation - call your stuff mylistor thelist, or for example not list .

: OP aks > 1 , , sublist ( ;-), :

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

sublist[0:0] - sublist, , , .

+16
>>> someList = [[1,2,3],[4,5,6],[7,8,9]]
>>> someList = [[9] + i for i in someList]
>>> someList
[[9, 1, 2, 3], [9, 4, 5, 6], [9, 7, 8, 9]]

(someList, python)

+12

insert, :

>>> numberlists = [[1,2,3],[4,5,6]]
>>> for numberlist in numberlists:
...  numberlist.insert(0,9)
...
>>> numberlists
[[9, 1, 2, 3], [9, 4, 5, 6]]

, succintly

[numberlist.insert(0,9) for numberlist in numberlists]

, , ,

newnumberlists = [[9] + numberlist for numberlist in numberlists]
+2

,
, deques * :

>>> mylist = [[1,2,3],[4,5,6],[7,8,9]]

>>> from collections import deque
>>> mydeque = deque()
>>> for li in mylist:
...   mydeque.append(deque(li))
...
>>> mydeque
deque([deque([1, 2, 3]), deque([4, 5, 6]), deque([7, 8, 9])])
>>> for di in mydeque:
...   di.appendleft(9)
...
>>> mydeque
deque([deque([9, 1, 2, 3]), deque([9, 4, 5, 6]), deque([9, 7, 8, 9])])

* Deques - ( "" " " ). Deques -, deque O (1) .

, , :
,
, , .

+2
#!/usr/bin/env python

def addNine(val):
    val.insert(0,9)
    return val

if __name__ == '__main__':
    s = [[1,2,3],[4,5,6],[7,8,9]]
    print map(addNine,s)

:

[[9, 1, 2, 3], [9, 4, 5, 6], [9, 7, 8, 9]]
0

Source: https://habr.com/ru/post/1711549/


All Articles