What's the difference between () vs [] vs {}?

后端 未结 4 754
轻奢々
轻奢々 2020-12-13 04:56

What\'s the difference between () vs [] vs {} in Python?
They\'re collections? How can I tell when to use which?

相关标签:
4条回答
  • 2020-12-13 05:18

    () - tuple

    A tuple is a sequence of items that can't be changed (immutable).

    [] - list

    A list is a sequence of items that can be changed (mutable).

    {} - dictionary or set

    A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, {} can also represent a set of unique values (mutable).

    0 讨论(0)
  • 2020-12-13 05:18
    () - tuple
    [] - list
    {} - dictionary
    

    All Python tutorials should cover this. Here is a good place to start.

    0 讨论(0)
  • 2020-12-13 05:23

    In addition to the tuple, list and dict given by the other answers, {} also denotes a set literal in python 2.7 and python 3.1. (This makes sense because set elements act like the keys of a dict).

    0 讨论(0)
  • 2020-12-13 05:24
    • () is a tuple: An immutable collection of values, usually (but not necessarily) of different types.
    • [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
    • {} is a dict: Use a dictionary for key value pairs.

    For the difference between lists and tuples see here. See also:

    • Python Tuples are Not Just Constant Lists
    0 讨论(0)
提交回复
热议问题