Ask Your Question
0

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

2 Answers

Sort by ยป oldest newest most voted
0

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

slelievre gravatar image

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

Instead of modifying the lists in place, one could create new lists.

One way would be to make the new list of lists using slices of the old lists.

Here is one way that could be done.

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-02-23 12:23:44 +0100

Cyrille gravatar image

updated 2021-02-23 18:10:46 +0100

I have understud. insert modifies directly Z

edit flag offensive delete link more

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: 40 times

Last updated: Feb 23