Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?

后端 未结 17 2017
旧巷少年郎
旧巷少年郎 2020-12-29 01:24

In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably.

When should I use one or the other, and why?

相关标签:
17条回答
  • 2020-12-29 01:30

    (1,2,3) and [1,2,3] can be used interchangeably in rare conditions.

    So (1,2,3) is a tuple and is immutable. Any changes you wish to make need to overwrite the object.

    [1,2,3] is a list and elements can be appended and removed.

    List has more features than a tuple.

    0 讨论(0)
  • 2020-12-29 01:30

    (1,2,3) is a tuple while [1,2,3] is a list. A tuple is an immutable object while a list is mutable.

    0 讨论(0)
  • 2020-12-29 01:31

    Tuples are a quick\flexible way to create composite data-types. Lists are containers for, well, lists of objects.

    For example, you would use a List to store a list of student details in a class.

    Each student detail in that list may be a 3-tuple containing their roll number, name and test score.

    `[(1,'Mark',86),(2,'John',34)...]`
    

    Also, because tuples are immutable they can be used as keys in dictionaries.

    0 讨论(0)
  • 2020-12-29 01:31

    As others have mentioned, Lists and tuples are both containers which can be used to store python objects. Lists are extensible and their contents can change by assignment, on the other hand tuples are immutable.

    Also, lists cannot be used as keys in a dictionary whereas tuples can.

    0 讨论(0)
  • 2020-12-29 01:33
    • A tuple might represent a key in dictionary, because it's immutable.
    • Use lists if you have a collection of data that doesn't need random access.
    0 讨论(0)
  • 2020-12-29 01:33

    a = (1,2,3) is a tuple which is immutable meaning you can't add anything into a b = [1,2,3] is a list in python which is immutable meaning you can make changes into 'b' either delete or add numbers into it.

    0 讨论(0)
提交回复
热议问题