Beginner python set intersection error
16,650
Solution 1
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.
Solution 2
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.
Solution 3
On Python 2.7+, this is syntax for intersections using set operators:
>>> rare = {"word1", "word4", "word5"}
>>> freq = {"word1", "word2", "word3"}
>>> rare & freq
{'word1'}
Solution 4
unique = set(rare).intersection(freq)
print(unique)
Solution 5
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)
Author by
some1
Updated on June 09, 2022Comments
-
some1 almost 2 years
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?