Ask Your Question

# Adding a 0 in variable place in a list

I was expecting that the command

Z=[[141,163,127],[107,132,117],[85,116,120],[121,131,128]]
ZZ=[Z[i].insert(i,0) for i in range(len(Z))]


will insert a 0 in rank 'i' for each element of Z but it returns [None, None, None, None]. Need help Thanks

edit retag close merge delete

## Comments

I have understud. insert modifies directly Z

( 2021-02-23 12:23:44 +0100 )edit

## 2 Answers

Sort by ยป oldest newest most voted

As you correctly understood, insert modifies a list in-place, returning None.

An alternative is to create new lists, e.g. using slices of the old lists.

Here is one way to do that.

sage: Z = [[141, 163, 127], [107, 132, 117], [85, 116, 120], [121, 131, 128]]
sage: ZZ = [z[:i] + [0] + z[i:] for i, z in enumerate(Z)]
sage: ZZ
[[0, 141, 163, 127], [107, 0, 132, 117], [85, 116, 0, 120], [121, 131, 128, 0]]

more

## Comments

Nice. I have not thinked to this nice possibility.

( 2021-02-24 09:00:39 +0100 )edit

Another option, which is just a small modification of the original code:

sage: Z = [[141,163,127],[107,132,117],[85,116,120],[121,131,128]]
sage: ZZ = copy(Z)
sage: [ZZ[i].insert(i,0) for i in range(len(ZZ))]; ZZ
[[0, 141, 163, 127], [107, 0, 132, 117], [85, 116, 0, 120], [121, 131, 128, 0]]

more

## Comments

Careful: use deepcopy instead of copy, otherwise Z ends up changed too.

Or write ZZ = [copy(z) for z in Z].

( 2021-03-25 21:15:57 +0100 )edit

Yes, you are right. Thanks for the correction.

( 2021-03-25 23:31:31 +0100 )edit

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2021-02-23 12:19:49 +0100

Seen: 205 times

Last updated: Mar 25 '21