apexprogramming
apexprogramming

Reputation: 433

Append list every Nth index from another list

I have two lists:

gizmos = [('gizmo1', 314),
          ('gizmo1', 18),
          ('gizmo1', 72),
          ('gizmo1', 2),
          ('gizmo1', 252)]

owner =  ['owner1','owner3','owner32']

My goal result is to two combine both list into a new list, looping every other element:

newlist= [('owner1','gizmo1', 314),
          ('gizmo1', 18),
          ('owner3','gizmo1', 72),
          ('gizmo1', 2),
          ('owner32','gizmo1', 252)]

I attempted to zip the 3 lists but due to the lengths not matching this does not work.

Upvotes: 1

Views: 110

Answers (2)

superb rain
superb rain

Reputation: 5521

If it's ok to modify the list instead of creating a new one:

for i, o in enumerate(owner):
    gizmos[2*i] = o, *gizmos[2*i]

Or:

gizmos[::2] = ((o, *g) for o, g in zip(owner, gizmos[::2]))

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24233

You could do that with a list comprehension:

gizmos = [('gizmo1', 314), ('gizmo1', 18), ('gizmo1', 72), ('gizmo1', 2), ('gizmo1', 252)]

owner =  ['owner1','owner3','owner32']

newlist = [(owner[i//2], *giz ) if i%2==0 else giz for i, giz in enumerate(gizmos)]
print(newlist)
# [('owner1', 'gizmo1', 314), ('gizmo1', 18), ('owner3', 'gizmo1', 72), ('gizmo1', 2), ('owner32', 'gizmo1', 252)]

For odd indices, we just take the item from gizmos.

For even indices, we create a new tuple containing the owner, and the items of the original gizmo tuple which we unpack.

Upvotes: 4

Related Questions