What is the difference between sets and lists in P

2019-01-10 08:16发布

问题:

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?

回答1:

There's a huge difference.

  1. Sets can't contain duplicates
  2. Sets are unordered
  3. In order to find an element in a set, a hash lookup is used (which is why sets are unordered). This makes __contains__ (in operator) a lot more efficient for sets than lists.
  4. Sets can only contain hashable items (see #3). If you try: 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.



回答2:

sets — Unordered collections of unique elements

lists - ordered collections of elements

sets allows you to do operations such as intersection, union, difference, and symmetric 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.



回答3:

Set represents a collection of distinct elements. In python, sets are mainly used for two reasons (Book: Data Science from Scratch, Joel Gruce):

  1. 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.

  2. To find a distinct items in a collections. Programmers use sets much less frequently than dicts and lists.



回答4:

Some more differences are:

  1. List can be 2-D whereas a set can't.
  2. As list are ordered (IE. have serial number) list are comparatively slow to execute whereas sets are fast.
  3. List in python is like Array of java or c.
  4. Printing a set almost always provide different sequence of output.


回答5:

Set

A set is a collection which is unordered and unindexed, and doesnt allow duplicates. In Python, sets are written with curly brackets.

# example set
newset = {"one", "two", "three"}
  • You cannot access items in a set by referring to an index
  • Sets are mutable
  • They are useful for checking for duplicates

List

A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

# example list
newlist =["one", "two", "three"]
  • You access the list items by referring to the index number
  • Lists are mutable.


标签: python list set