sam
sam

Reputation: 19164

list operations using list comprehension

I have a list.

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

I want to use list comprehension & wanted to create output as :

output1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

output2:
('value', 1)
('value', 2)
'
'
('value', 20)

I can create output1 and output2 using for loop but I dont have idea that how I can use list comprehension for the same.

If any one knows this, kindly let me know.

thanks in advance.

Upvotes: 0

Views: 170

Answers (3)

Marcin
Marcin

Reputation: 49826

Here's JF Sebastians's grouper, which solves your first problem:

 from itertools import izip_longest, repeat
 izip_longest(*[iter(a)]*4, fillvalue=None)

For your second: zip(repeat('value'), a)

Upvotes: 4

Abhijit
Abhijit

Reputation: 63727

For the First you can do something like

>>> [a[i:i+4] for i in range(0,len(a),4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

For the Second you can simply read and generate the tuples with value as the first item

>>> [('value',i) for i in a]
[('value', 1), ('value', 2), ('value', 3), ('value', 4), ('value', 5), ('value', 6), ('value', 7), ('value', 8), ('value', 9), ('value', 10), ('value', 11), ('value', 12), ('value', 13), ('value', 14), ('value', 15), ('value', 16), ('value', 17), ('value', 18), ('value', 19), ('value', 20)]

another version using itertools.izip_longest though the above is more redable

list(itertools.izip_longest([],a,fillvalue='value'))

Upvotes: 8

mshsayem
mshsayem

Reputation: 18008

output1 = [a[i:i+4] for i in xrange(0,len(a),4)]
output2 = [('value',i) for i in a]

Upvotes: 4

Related Questions