2

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?

2 Answers2

2

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
0
inp='sample'
n=5
print [(inp,i) for i in range(n)]

it Shows O/P as:

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

Sagar T
  • 89
  • 1
  • 1
  • 11