1

I have two lists

l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66,]

I want to display them on same lines

"list1 text"  "list2 text"

l1-1   , l2-1
l1-2   , l2-2

and so on

so that if list elements finish then it should display blank "" in front of it but other side shows its own elements like

for a,b in l1,l2
     <td>a</td><td> b </td>
2
  • docs.python.org/2/library/functions.html#zip Commented Apr 26, 2013 at 6:14
  • 1
    BTW this is not called "looping in parallel". that word refers mainly to parallel computations. Commented Apr 26, 2013 at 6:21

7 Answers 7

4

You can use izip_longest with a fillvalue of whitespace,

>>> from itertools import izip_longest
>>> for a,b in izip_longest(l1,l2,fillvalue=' '):
...     print a,b
... 
1 1
2 2
3 3
4 4
5 5
6 6
7 7
  8
  9
  77
  66
Sign up to request clarification or add additional context in comments.

1 Comment

I don't really know how is that possible. You have to show us your code.
3

Something like this?

from itertools import izip_longest
l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66,]

for a,b in izip_longest(l1,l2, fillvalue=''):
    print '"'+str(a)+'"','"'+str(b)+'"'

Out:

"1" "1"
"2" "2"
"3" "3"
"4" "4"
"5" "5"
"6" "6"
"7" "7"
"" "8"
"" "9"
"" "77"
"" "66"

Comments

1

Itertools.izip_longest can be used to combine the two lists, the value None will be used as a placeholder value for "missing" items in the shorter list.

Comments

1
>>>l1= [1,2,3,4,5,6,7]
>>l2 = [1,2,3,4,5,6,7,8,9,77,66,]
>>>n = ((a,b) for a in l1 for b in l2)
>>>for i in n:
       i

for more details please go through this link: Hidden features of Python

1 Comment

This is nesting the two loops, which doesn't seem to be what is asked for. Incidentally, you can use for i in itertools.product(l1, l2): to do the same thing
1
>>> l1= [1,2,3,4,5,6,7]
>>> l2 = [1,2,3,4,5,6,7,8,9,77,66,]
>>> def render_items(*args):
...     return ''.join('<td>{}</td>'.format('' if i is None else i) for i in args)
... 
>>> for item in map(render_items, l1, l2):
...     print item
... 
<td>1</td><td>1</td>
<td>2</td><td>2</td>
<td>3</td><td>3</td>
<td>4</td><td>4</td>
<td>5</td><td>5</td>
<td>6</td><td>6</td>
<td>7</td><td>7</td>
<td></td><td>8</td>
<td></td><td>9</td>
<td></td><td>77</td>
<td></td><td>66</td>

Comments

1
l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66]
maxlen = max(len(l1),len(l2))
l1_ext = l1 + (maxlen-len(l1))*[' ']
l2_ext = l2 + (maxlen-len(l2))*[' ']
for (a,b) in zip(l1_ext,l2_ext):
    print a,b

Comments

1
l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66]
for (a,b) in map(lambda a,b:(a or ' ',b or ' '), l1, l2):
    print a,b

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.