1

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.

superb rain
  • 5,300
  • 2
  • 11
  • 25
apexprogramming
  • 403
  • 2
  • 14
  • Set up to [iterate the `gizmos` in chunks of 2](https://stackoverflow.com/questions/8290397/how-to-split-an-iterable-in-constant-size-chunks), and then do the `zip`. – Karl Knechtel Dec 09 '20 at 00:06

2 Answers2

4

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.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

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]))
superb rain
  • 5,300
  • 2
  • 11
  • 25