Python Sets | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python Sets

I can't understand really why do I have to chose sets. I mean, someone says that they use less memory than lists. But we said also that they are not indexed and that we can't friendly operate on them. So when we have a long list is really more effective and cheap to convert a list into a set than operate directly on the list? Thank you :)

15th Mar 2018, 9:36 PM
Rainbow238
Rainbow238 - avatar
5 Answers
+ 3
The important thing about sets is that you can’t duplicate values. It’s good if you require all values to be unique, which a list does not have. Also, sets retrieve values much faster than lists because they hash the values.
15th Mar 2018, 9:45 PM
Ariela
Ariela - avatar
+ 3
Also the ease of union or difference between sets. A-B gives all the elements in set A that are not in set B A&B gives all the elements that occur in set A and set B I.e the overlapping elements etc see lesson below https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2464/
16th Mar 2018, 6:01 AM
Louis
Louis - avatar
+ 1
Well, I’ve used in a game where I wanted to add a weapon. I only wanted the player to have one of each weapon (they each had unique values and properties.) So every time the player picked up the sword, I would add it and it would only add if it wasn’t already in there. I didn’t have to check if it was in there because python did it for me.
15th Mar 2018, 9:53 PM
Ariela
Ariela - avatar
0
@Ariela, so I can use the conversion if I want to erase all the repetition in a list, that's right? Can you give me an example in which I force, using sets, the unicity of the inside Elements, please?
15th Mar 2018, 9:49 PM
Rainbow238
Rainbow238 - avatar
0
@Ariela thank you really much :)
15th Mar 2018, 10:06 PM
Rainbow238
Rainbow238 - avatar