In Java we have HashSet<Integer>
, I need similar structure in Python to use contains like below:
A = [1, 2, 3]
S = set()
S.add(2)
for x in A:
if S.contains(x):
print "Example"
Could you please help?
In Java we have HashSet<Integer>
, I need similar structure in Python to use contains like below:
A = [1, 2, 3]
S = set()
S.add(2)
for x in A:
if S.contains(x):
print "Example"
Could you please help?
Just use a set:
>>> l = set()
>>> l.add(1)
>>> l.add(2)
>>> 1 in l
True
>>> 34 in l
False
The same works for lists:
>>> ll = [1,2,3]
>>> 2 in ll
True
>>> 23 in ll
False
Edit:
Note @bholagabbar's comment below that the time complexity for in
checks in lists and tuples is O(n) on average (see the python docs here), whereas for sets it is on average O(1) (worst case also O(n), but is very uncommon and might only happen if __hash__
is implemented poorly).
s.contains(x)
(ie what the OP asked), and b) that the same syntactic construct can be used to test for membership in lists. Having said that, I can include a pointer to bholagabbar's comment, if its helpful. –
Sonnier In Python, there is a built-in type, set
.
The major difference from the hashmap
in Java is that the Python set
is not typed,
i.e., it is legal to have a set {'2', 2}
in Python.
Out of the box, the class set
does not have a contains()
method implemented.
We typically use the Python keyword in
to do what you want, i.e.,
A = [1, 2, 3]
S = set()
S.add(2)
for x in A:
if x in S:
print("Example")
If that does not work for you, you can invoke the special method __contains__()
, which is NOT encouraged.
A = [1, 2, 3]
S = set()
S.add(2)
for x in A:
if S.__contains__(x):
print("Example")
in
keyword, as in if x in A
, the __contains__()
method on A (i.e. a set
's __contains__()
method) will be invoked. Its true that you shouldn't invoke it directly, since its invoked by using the in
keyword. –
Sonnier © 2022 - 2024 — McMap. All rights reserved.
if x in S
means contains? – Undressed