Reputation: 866
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?
Upvotes: 2
Views: 840
Reputation: 89
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)]
Upvotes: 0
Reputation: 402483
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.
Upvotes: 2