NULL.Dude
NULL.Dude

Reputation: 219

printing formated set list of values

I am comparing two lists using set.difference I want each value that is not in the list a that is in list b to be printed on its own line, however, the set is not letting me. code and output are below.

import pprint

a = [1,2,3,5,6,8,9,10]
b = [13,452,3,4,5,6,7,8,9,10,11]
c = []
difference = set(b).difference(a)
c.append(difference)
#print c
for item in c:
    pprint.pprint (str(item))

The output I am getting is this:

'set([4, 7, 11, 13, 452])'
>>> 

The output I would like would be this:

>>>
4
7
11
13
452
>>>

Upvotes: 1

Views: 43

Answers (3)

DeepSpace
DeepSpace

Reputation: 81654

EDIT

Didn't notice this question is tagged with Python 2.7. I'll leave it for future googlers. However, this answer can be used in later versions of Python 2.7 by using
from __future__ import print_function


By doing c.append(difference) you are creating a list that contains the entire difference set.

This should do the trick:

difference = set(b).difference(a)
for num in difference:
    print(num)

Or a single-liner by using * expansion:

print(*difference , sep='\n')

Upvotes: 2

Mark
Mark

Reputation: 5239

I believe you have made a mistake, you're appending difference (a list) to c (also a list). Therefore when you're looping through c which contains a list, you're printing out that entire list. And not the individual values of that list.

In my example below you're assigning the difference to c directly, so c does not contain a list with your values but c is the list with your values.

import pprint

a = [1,2,3,5,6,8,9,10]
b = [13,452,3,4,5,6,7,8,9,10,11]
c = set(b).difference(a)

for item in c:
    pprint.pprint (str(item))

Upvotes: 2

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

You can do this like this:

difference = set(b).difference(a)
c.append(difference)
for item in c:
    print(*item, sep='\n')

but the c is redundant in your code because it just appends a set into a list that has one item so, you can remove with and just do this:

difference = set(b).difference(a)
print(*difference, sep='\n')

Upvotes: 2

Related Questions