Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner python set intersection error

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?

like image 879
some1 Avatar asked Feb 14 '12 06:02

some1


People also ask

How do you calculate intersection in Python?

We can use a method called intersection in python and set intersection operator, i.e. &, to get the intersection of two or more sets. The set intersection operator only works with sets, but the set intersection() method can be used with any iterable, like strings, lists, and dictionaries.

How do you use intersection in sets?

The intersection of sets can be denoted using the symbol '∩'. As defined above, the intersection of two sets A and B is the set of all those elements which are common to both A and B. Symbolically, we can represent the intersection of A and B as A ∩ B.

What is the time complexity of python set intersection?

What is the Time Complexity of Set Intersection in Python? The runtime complexity of the set. intersection() method on a set with n elements and a set argument with m elements is O(min(n, m)) because you need to check for the smaller set whether each of its elements is a member of the larger set.


2 Answers

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.

like image 83
mgibsonbr Avatar answered Sep 28 '22 18:09

mgibsonbr


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

>>> rare = {"word1", "word4", "word5"}
>>> freq = {"word1", "word2", "word3"}
>>> rare & freq
{'word1'}
like image 35
wim Avatar answered Sep 28 '22 17:09

wim