Ask Your Question
1

Adding a 0 in variable place in a list

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

Cyrille gravatar image

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 flag offensive close merge delete

Comments

I have understud. insert modifies directly Z

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

2 Answers

Sort by ยป oldest newest most voted
0

answered 2021-02-23 22:04:11 +0100

slelievre gravatar image

updated 2021-03-24 18:18:23 +0100

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]]
edit flag offensive delete link more

Comments

Nice. I have not thinked to this nice possibility.

Cyrille gravatar imageCyrille ( 2021-02-24 09:00:39 +0100 )edit
0

answered 2021-03-25 18:45:55 +0100

Juanjo gravatar image

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]]
edit flag offensive delete link more

Comments

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

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

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

Yes, you are right. Thanks for the correction.

Juanjo gravatar imageJuanjo ( 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

Question Tools

1 follower

Stats

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

Seen: 246 times

Last updated: Mar 25 '21