Aymen Derradji Aymen Derradji - 7 months ago 18
Python Question

How to zip two arrays without truncating to the shortest array?

im trying to write a script in python that gives me each item in array A and what it corresponds in array B

let's say array A are Customers
and array B are rooms

A = 'Customer 1','Customer 2','Customer 3','Customer 4'
B = 'room 1','room 2','room 3','room 4'

for Customers,rooms in zip(A,B):
print Customers +' is in '+ rooms


and the output is:

Customer 1 is in room 1
Customer 2 is in room 2
Customer 3 is in room 3
Customer 4 is in room 4


now what if we have only 3 rooms in array B
the output well ignore Customer 4

Customer 1 is in room 1
Customer 2 is in room 2
Customer 3 is in room 3


my quistion is how to make it write for me
all rooms are reserved
if A>b

Customer 1 is in room 1
Customer 2 is in room 2
Customer 3 is in room 3
customer 4 all rooms are reserved

Answer

You can use itertools.izip_longest over zip to fill in the shorter list with None values and update your logic like below:

from itertools import izip_longest

for customer, room in izip_longest(A, B):
    if room:
        print customer + ' is in ' + room
    else:
        print customer + ' all rooms are reserved'