5
rare = (["word1","word4","word5"])
freq = (["word1","word2","word3"])
unique = rare.intersection(freq)
print unique

error: AttributeError: 'list' object has no attribute 'intersection'

Am I not creating the sets correctly? They look like the examples in documentation -- but I can't seem to use normal set methods on them.

What is the proper syntax for creating sets if these are lists?

0

7 Answers 7

7

This way you're not creating sets, just regular lists. Use the set function:

rare = set(["word1","word4","word5"])
freq = set(["word1","word2","word3"])

Maybe you're confusing sets with tuples. A tuple is created with expressions between parenthesis, but you must provide at least a comma:

("this", "is", "a", "tuple")
("anotherone",)

Tuples are like immutable lists, but they're not sets.

2
  • Thank you, that was driving me frickin' crazy.
    – some1
    Feb 14, 2012 at 6:56
  • 1
    Glad it helped! If you're using a recent Python, see also Tavian Barnes' answer, since it's more concise.
    – mgibsonbr
    Feb 14, 2012 at 7:05
4

On Python 2.7+, this is syntax for intersections using set operators:

>>> rare = {"word1", "word4", "word5"}
>>> freq = {"word1", "word2", "word3"}
>>> rare & freq
{'word1'}
3

You want this:

rare = {"word1", "word4", "word5"}
freq = {"word1", "word2", "word3"}
unique = rare.intersection(freq)
print(unique)

Note that the syntax for set literals has been backported as far as Python 2.7.

2
  • @JoelCornett: Why not? It compiles fine, it executes fine, it does what the OP wants. Feb 14, 2012 at 6:58
  • 2
    @MichaelFoukarakis I think it depends on Python version. For instance, 2.5 doesn't accept it, 2.7 does.
    – mgibsonbr
    Feb 14, 2012 at 7:01
1
unique = set(rare).intersection(freq)
print(unique)
1
  • That's a cleaner way of doing it.
    – coder3
    May 27, 2020 at 7:07
1

u can do it like that its shorter i guess :

rare = (["word1","word4","word5"])
freq = (["word1","word2","word3"])
unique = set(rare).intersection(set(freq))
print(unique)
0

Your solution had an issue because both 'rare' and 'freq' objects were arrays. They must be converted to a set data type. I use '&' rather than 'intersection' as it seems neater.

unique = set(rare) & set(freq)
print(unique)
0
-1

This works for me

unique = set(rare).intersection(freq)
print(len(unique))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.