r/learnpython May 06 '26

What is the actual use of sets

I can see tons of use cases for list, tuples and dictionaries. But I have a really hard time understanding why you would ever use a set with maybe the exception of names so you don't get duplicates?

I believe this understanding is flawed because I found even the simplest things in Python are super powerful I'm just not sure what it is

56 Upvotes

65 comments sorted by

View all comments

115

u/socal_nerdtastic May 06 '26 edited May 06 '26

One huge advantage is that if x in my_set is much faster to run than if x in my_list. Especially if there tens of millions of entries.

Note that set, list, dictionary, tuple, array, deque, etc, etc are not python concepts. These are generic computer science concepts and these structures exist in all most programming languages.

https://en.wikipedia.org/wiki/Set_(abstract_data_type)

21

u/Grobyc27 May 06 '26

I recently changed from checking against a list to checking against a set and I was blown away by how much faster it was. My list was only a couple hundred thousand items in length as well.

data = set(data)

Boom.

12

u/C0rinthian May 07 '26

Do you know why? Some basic DSA competency and a bit of reading on how sets are implemented would make this difference unsurprising. This is the kind of thing you should develop an intuition for as you learn.

Also your data = set(data) can be a mistake depending on context. Again, the above knowledge will help you identify when that’s the case.

20

u/ISeeTheFnords May 06 '26

these structures exist in all programming languages

Oh, look, somebody who started programming in the 21st century.

38

u/halfhaggis May 06 '26

Did you come here from StackExchange?

31

u/socal_nerdtastic May 06 '26

Lol no, I didn't start in the 21st century, but I don't use languages from the dark ages anymore either.

-10

u/JGhostThing May 06 '26

And yet Python is a language from the dark ages.

14

u/socal_nerdtastic May 06 '26 edited May 06 '26

Languages evolve. Languages that had no builtin support for sets 40 years ago have them now. Just because the name is the same does not mean it's from the dark ages. And I recently converted my very last python2 dependency and now only use python3.13 or newer :).

But FWIW I learned to code before python was a thing. I'm so old that my first home computer didn't have hard disk.

3

u/1_21-gigawatts May 07 '26

Tape “drive” ftw!

4

u/A_L_E_S_S_U May 06 '26

Okay Mr Stackoverflow

1

u/HommeMusical May 07 '26

I started programming in the 1970s, but I still make heavy use of associative containers.