11

I'm trying to output the values of 2 lists side by side using list comprehension. I have an example below that shows what I'm trying to accomplish. Is this possible?

code:

#example lists, the real lists will either have less or more values
a = ['a', 'b', 'c,']
b = ['1', '0', '0']

str = ('``` \n'
       'results: \n\n'
       'options   votes \n'
       #this line is the part I need help with: list comprehension for the 2 lists to output the values as shown below
       '```')

print(str)

#what I want it to look like:
'''
results:

options  votes
a        1
b        0
c        0
''' 
hwhat
  • 326
  • 1
  • 5
  • 14

5 Answers5

19

You can use the zip() function to join lists together.

a = ['a', 'b', 'c']
b = ['1', '0', '0']
res = "\n".join("{} {}".format(x, y) for x, y in zip(a, b))

The zip() function will iterate tuples with the corresponding elements from each of the lists, which you can then format as Michael Butscher suggested in the comments.

Finally, just join() them together with newlines and you have the string you want.

print(res)
a 1
b 0
c 0
SCB
  • 5,821
  • 1
  • 34
  • 43
  • This is what I was looking for, thanks. Is there a way to format it so it'll have x spaces in between the values? – hwhat Jan 02 '18 at 01:23
  • You might want to look at [padding and aligning strings](https://pyformat.info/#string_pad_align). That link is a great tool in general for learning about `.format()`. – SCB Jan 02 '18 at 02:35
  • For quick reference, if you did something like `"{:>5} {:5}".format(x, y)` that would give you columns of minimum width 5, with the left column right aligned. – SCB Jan 02 '18 at 02:37
  • could you have something like a min width of the longest value in the list? – hwhat Jan 02 '18 at 02:53
  • You can nest format values like `"{:>{}} {:{}}".format(x, width_x, y, width_y)`. Then to calculate the width you can just find the `max` length in the list. E.g.`width_x = max(len(x) for x in a)`. – SCB Jan 02 '18 at 03:09
  • [Another good relevant read for this case](https://www.python.org/dev/peps/pep-3101/#format-specifiers). – SCB Jan 02 '18 at 03:10
7

This works:

a = ['a', 'b', 'c']
b = ['1', '0', '0']

print("options  votes")

for i in range(len(a)):
    print(a[i] + '\t ' + b[i])

Outputs:

options  votes
a        1
b        0
c        0
Ivan86
  • 5,695
  • 2
  • 14
  • 30
3
from __future__ import print_function  # if using Python 2

a = ['a', 'b', 'c']
b = ['1', '0', '0']

print("""results:

options\tvotes""")

for x, y in zip(a, b):
    print(x, y, sep='\t\t')
Ronie Martinez
  • 1,254
  • 1
  • 10
  • 14
0
[print(x,y) for x,y in zip(list1, list2)]

Note the square brackets enclosing the print statement.

PJ_
  • 473
  • 5
  • 9
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. –  Apr 27 '22 at 19:52
0

This code will work for variable lengths of lists too:

a = ['aaaaaaa', 'b', 'c']
b = ['1', '000000000000', '0', '2']

max_a = max(len(x) for x in a)
max_b = max(len(y) for y in b)

if len(a)>len(b):
    new_b = b + [' ']*(len(a)-len(b))
    for i in range(len(a)):
        print(f"{a[i]:{max_a}}|{new_b[i]:{max_b}}")
else:
    new_a = a + [' ']*(len(b)-len(a))
    for j in range(len(b)):
        print(f"{new_a[j]:{max_a}}|{b[j]:{max_b}}")

Output:

aaaaaaa|1           
b      |000000000000
c      |0           
       |2           
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 26 '23 at 14:03