Alex Rosenblum
Alex Rosenblum

Reputation: 3

How do I insert multiple copies of an integer into the middle of a list?

My assignment is this:

Let L be a list of non-negative integers. Write an expression that replaces the centermost element of L with that many copies of 0. Note that "centermost" here is defined the usual way for a list of odd length, but may seem a bit unusual for a list of even length. So, for example, if L = [1, 2, 3, 4, 5], the modified value of L will be [1, 2, 0, 0, 0, 4, 5], but if L = [1, 2, 0, 3], the modified value would be [1, 2, 3], as the 0 – here the centermost element of an even-length list – would be replaced with 0 copies of 0.

The expression I came up with is

L[len(L)/2] = [0] * L[(len(L)/2)]

and output for L = [1, 2, 3, 4, 5] is

[1, 2, [0, 0, 0], 4, 5]

I need to eliminate that inner list element such that the zeroes are part of the outer list. We are restricted to a single line and no for/while loops.

Upvotes: 0

Views: 111

Answers (2)

ekhumoro
ekhumoro

Reputation: 120588

Since Python 2.3, it is possible to assign to slices:

>>> L = [1, 2, 3, 4, 5]
>>> L[len(L)//2:len(L)//2 + 1] = [0] * L[(len(L)//2)]
>>> L
[1, 2, 0, 0, 0, 4, 5]   
>>> L = [1, 2, 0, 3]
>>> L[len(L)//2:len(L)//2 + 1] = [0] * L[(len(L)//2)]
>>> L
[1, 2, 3]

Upvotes: 1

Reut Sharabani
Reut Sharabani

Reputation: 31339

As @saulspatz suggests use slicing:

middle = len(L) / 2
L = L[:middle] + ([0] * L[middle]) + L[middle + 1:]

Upvotes: 1

Related Questions