Basic comparison
- list: ordered, mutable, duplicable
- set:
set([1, 2, 3, 4])
, not duplicable, not ordered
# set's operation
a = set([1, 2, 3])
b = set([2, 3, 4])
a.intersection(b) # equivalent to c = a & b, return set([2,3])
c.issubset(a) # return true, equivalent to c <= a
c.issuperset(a) # return false, equivalent to c >= a
a.difference(b) # return set([1]), equivalent to a-b
a.symmetric_difference(b) # return set([1,4]), equivalent to a ^ b
- tuple: immutable, ordered, duplicable
When to use what?
Apart from immutable and mutable feature between tuple and list(many good feature of immutable data structure), tuple stores heterogeneous elements list (a, ‘fdsa’, 123) etc. while list stores homogeneous elements. Set requires items to be hashable to guarentee the unique element feature which make it faster for accessing.
Usage
Definition:
- list = [1,2,3]
- tuple = (1,2,3)
- set = {1,2,3}
Access: List and tuple are accessed by index eg. list[0], tuple[1]. set use the pop method.
Reference
In Python, when to use a Dictionary, List or Set? Python Programming/Tuples and Sets Chapter 4. Dictionaries and Sets Lists vs. Tuples