First time here? Check out the FAQ!

Ask Your Question
1

Adding a 0 in variable place in a list

asked 4 years ago

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

Preview: (hide)

Comments

I have understud. insert modifies directly Z

Cyrille gravatar imageCyrille ( 4 years ago )

2 Answers

Sort by » oldest newest most voted
0

answered 4 years ago

slelievre gravatar image

updated 4 years ago

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]]
Preview: (hide)
link

Comments

Nice. I have not thinked to this nice possibility.

Cyrille gravatar imageCyrille ( 4 years ago )
0

answered 4 years ago

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]]
Preview: (hide)
link

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 ( 4 years ago )

Yes, you are right. Thanks for the correction.

Juanjo gravatar imageJuanjo ( 4 years ago )

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: 4 years ago

Seen: 278 times

Last updated: Mar 25 '21