Inserting while itterating
Jeremy Bowers
jerf at jerf.org
Sat Jan 17 22:27:41 EST 2004
On Wed, 14 Jan 2004 09:43:01 +0100, Thomas Guettler wrote:
> Hi,
>
> Simple excerise:
>
> You have a sorted list of integers:
> l=[1, 2, 4, 7, 8, 12]
>
> and you should fill all gaps:
>
> result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>
> How would you code this?
>
> Constrain: The original list should be changed,
> don't create a copy.
>
> thomas
l[:] = [x for x in range(l[0], l[-1] + 1)]
If you care about timing, you'll want to compare against Peter Abel's
solution; I would not guarantee which is faster. All I can tell you is
which makes more sense to me when I read it.
Actually, maximal readability is
l[:] = [x for x in range(min(l), max(l) + 1)]
but that will *certainly* be less efficient if you know the list is sorted
then my first post.
More information about the Python-list
mailing list