📜  python set literal - Python (1)

📅  最后修改于: 2023-12-03 14:46:03.950000             🧑  作者: Mango

Python Set Literal

In Python, a set is a collection of unordered elements, without duplicates. There are several ways to create a set in Python, and one of them is by using set literals.

A set literal is a notation that allows you to define a set by enclosing its elements in curly braces {}. For example:

my_set = {1, 2, 3, 'a', 'b', 'c'}
print(my_set)

Output:

{1, 2, 3, 'a', 'b', 'c'}
Features of Set Literals
  • Duplicates are automatically removed: If you try to add an element that is already in the set, it will not be added again.
my_set = {1, 2, 3, 3, 3, 'a', 'a', 'b', 'b', 'c'}
print(my_set)

Output:

{1, 2, 3, 'a', 'b', 'c'}
  • Order is not guaranteed: Sets are implemented as hash tables, which means that the order of the elements is not guaranteed.
my_set = {2, 1, 3}
print(my_set)

Output:

{1, 2, 3}
  • Elements must be hashable: In order to be added to a set, elements must be hashable, which means that they must have a hash value that does not change during their lifetime. Most Python built-in types are hashable, including integers, floats, strings, tuples (if their elements are hashable), and frozensets.
my_set = {1, 2, 3, [4, 5, 6]}  # TypeError: unhashable type: 'list'
  • Empty sets must be defined as set literals: You cannot create an empty set using the constructor set(), because it would create an empty dictionary instead. To create an empty set, you must use the notation {}.
empty_set = set()  # Creates an empty dictionary, not an empty set
empty_set = {}  # Creates an empty dictionary, not an empty set
empty_set = set({})  # Creates an empty set
empty_set = {}  # Creates an empty dictionary, not an empty set
Advantages of Set Literals
  • Compact notation: Set literals provide a compact and readable notation for defining sets.
odd_numbers = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
  • Efficiency: Set literals are efficient because they can be created directly in memory, without the need to call a constructor.
odd_numbers = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}  # Faster than using set([1, 3, 5, 7, 9, 11, 13, 15, 17, 19])
  • Readability: Set literals make the code more readable and self-explanatory.
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Conclusion

Set literals are a convenient and efficient way to define sets in Python. They provide a compact and readable notation, and they can be created directly in memory without the need to call a constructor. However, when defining sets with complex or mutable elements, it may be necessary to use other methods, such as set comprehensions or the constructor set().