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

后端 未结 17 2018
旧巷少年郎
旧巷少年郎 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:42

    [1, 2, 3] is a list in which one can add or delete items.
    (1, 2, 3) is a tuple in which once defined, modification cannot be done.

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

    If you can find a solution that works with tuples, use them, as it forces immutability which kind of drives you down a more functional path. You almost never regret going down the functional/immutable path.

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

    (1,2,3)-tuple [1,2,3]-list lists are mutable on which various operations can be performed whereas tuples are immutable which cannot be extended.we cannot add,delete or update any element from a tuple once it is created.

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

    The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost.

    The tuple (1,2,3) is fixed (immutable) and therefore faster.

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

    Whenever I need to pass in a collection of items to a function, if I want the function to not change the values passed in - I use tuples.

    Else if I want to have the function to alter the values, I use list.

    Always if you are using external libraries and need to pass in a list of values to a function and are unsure about the integrity of the data, use a tuple.

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