0

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.

sam
  • 18,509
  • 24
  • 83
  • 116

3 Answers3

8

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'))
Abhijit
  • 62,056
  • 18
  • 131
  • 204
4
output1 = [a[i:i+4] for i in xrange(0,len(a),4)]
output2 = [('value',i) for i in a]
mshsayem
  • 17,557
  • 11
  • 61
  • 69
4

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)

Community
  • 1
  • 1
Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 2
    i dont know but its proper answer. i dont know why some people just downvotes and dont give reasons – sam Apr 18 '12 at 13:36