Is the only difference between sets and lists in Python the fact that you can use the union, intersect, difference, symmetric difference functions to compare two sets? Why can't these functions simply be applied to lists? In what situations are sets more useful than lists?
List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.
Lists can be used to store any data type or a mixture of different data types. Lists are mutable which is one of the reasons why they are so commonly used. Tuple is a collection of values separated by comma and enclosed in parenthesis. Unlike lists, tuples are immutable.
There's a huge difference.
__contains__
(in
operator) a lot more efficient for sets than lists.set(([1],[2]))
you'll get a TypeError
.In practical applications, lists are very nice to sort and have order while sets are nice to use when you don't want duplicates and don't care about order.
Also note that if you don't care about order, etc, you can use
new_set = myset.intersection(mylist)
to get the intersection between a set
and a list
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With