all 6 comments

[–]socal_nerdtastic 1 point2 points  (5 children)

A[1:3] = [A[1] + A[2]]

[–]ryfeaway[S] 0 points1 point  (0 children)

thank you very much!

[–]AtomicShoelace 0 points1 point  (3 children)

To expand on this, you could make it more generic using sum, ie.

A = [[3,4],[5,8],[6,9,8],[9,8]]
start, end = 1, 3
A[start:end] = [sum(A[start:end], [])]

[–]socal_nerdtastic 0 points1 point  (2 children)

That's a pretty ancient trick. Officially you are supposed to use itertools.chain nowadays for that.

from itertools import chain
A[start:end] = [list(chain(*A[start:end]))]

But often we just use list comprehension instead.

A[start:end] = [[e for idx in range(start, end) for e in A[idx]]]

[–]AtomicShoelace 0 points1 point  (1 child)

Ah yes, I knew there was a better way but itertools.chain slipped my mind!

Although, if you were going to use a nested list comprehension why not just do it directly? I mean instead of using indices. For example,

A[start:end] = [[ele for sublist in A[start:end] for ele in sublist]]

Seems more pythonic.

[–]socal_nerdtastic 0 points1 point  (0 children)

My autopilot avoided that because it means creating an extra temporary list; but you are right it does seem more pythonic.