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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Some more differences are:
Set
A set is a collection which is unordered and unindexed, and doesnt allow duplicates. In Python, sets are written with curly brackets.
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
There's a huge difference.
__contains__
(in
operator) a lot more efficient for sets than lists.set(([1],[2]))
you'll get aTypeError
.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
to get the intersection between a
set
and alist
.sets
— Unordered collections of unique elementslists
- ordered collections of elementssets
allows you to do operations such asintersection
,union
,difference
, andsymmetric difference
, i.e operations of math's set theory. Sets doesn't allow indexing and are implemented on hash tables.lists
are really variable-length arrays, not Lisp-style linked lists. In lists the elements are accessed by indices.Set represents a collection of distinct elements. In python, sets are mainly used for two reasons (Book: Data Science from Scratch, Joel Gruce):
For faster operation: in is a very fast operation on sets. If we have a large collection of elements and if we wish to perform membership test, in that case it is appropriate to use set instead of a list.
To find a distinct items in a collections. Programmers use sets much less frequently than dicts and lists.