StacyM
StacyM

Reputation: 1036

Is there a count type of method that you can use on a Python set?

For example (which did not work):

rock_group = ([])
if rock_group.count() <= 12:
    rock_group.add(a_rock)

I'm looking to count the number of items in a set and if it is less than 12, then add the object a_rock to the set.

I was hoping to write something quicker and more efficient than a for loop.

Upvotes: 2

Views: 66

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122536

You can use len(rock_group). Also your rock_group is currently a list, not a set.

To create a set you can write: rock_group = set(). This means the code becomes:

rock_group = set()
if len(rock_group) <= 12:
    rock_group.add(a_rock)

Upvotes: 7

Related Questions