Search code examples
pythonziptuplesalternate

Alternate ways in place of zip


I have below inputs,

inp = 'Sample'
n = 5

I would like to generate a list of tuples of n elements packing input with index. So that my output is,

[('Sample', 0), ('Sample', 1), ('Sample', 2), ('Sample', 3), ('Sample', 4)]

Below snippet does the work neat,

output = zip([inp]*n, range(n))

Just curious about alternate approaches to solve the same?


Solution

  • The most obvious solution (a list comprehension) has already been mentioned in the comments, so here's an alternative with itertools.zip_longest, just for fun -

    from itertools import zip_longest
    
    r = list(zip_longest([], range(n), fillvalue=inp))
    print(r)
    [('Sample', 0), ('Sample', 1), ('Sample', 2), ('Sample', 3), ('Sample', 4)]
    

    On python2.x, you'd need izip_longest instead.