列表和元组之间有什么区别?

时间:2022-09-05 00:29:50

What's the difference?

有什么区别呢?

What are the advantages / disadvantages of tuples / lists?

元组/列表的优点/缺点是什么?

15 个解决方案

#1


848  

Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

除了元组是不可变的,还有一个语义区别,应该指导他们的使用。元组是异构的数据结构。,它们的条目有不同的含义,而列表是同质序列。元组有结构,列表有顺序。

Using this distinction makes code more explicit and understandable.

使用这种区分使代码更加清晰易懂。

One example would be pairs of page and line number to reference locations in a book, e.g.:

例如,在一本书中,一个例子是成对的页面和行号,例如:

my_location = (42, 11)  # page number, line number

You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.

然后,您可以将其用作字典中的键来存储位置的注释。另一方面,列表可以用来存储多个位置。很自然地,人们可能想要从列表中添加或删除位置,所以列表是可变的是有意义的。另一方面,从现有的位置添加或删除项是没有意义的,因此元组是不可变的。

There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.

在某些情况下,您希望在现有的位置元组中更改项目,例如在遍历页面的行时。但是tuple不变性迫使您为每个新值创建一个新的位置元组。这看起来很不方便,但是使用像这样的不可变数据是值类型和函数编程技术的基础,这可以有很大的优势。

There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this ("Tuples are immutable, and usually contain an heterogeneous sequence ...").

在这个问题上有一些有趣的文章。“Python元组不只是常量列表”或“理解Python中的元组和列表”。官方的Python文档也提到了这一点(“元组是不可变的,并且通常包含一个异构的序列…”)。

In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.

在像Haskell这样的静态类型语言中,元组中的值通常有不同的类型,并且元组的长度必须是固定的。在列表中,所有的值都具有相同的类型,并且长度不是固定的。差别非常明显。

Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.

最后是Python中的namedtuple,这是有意义的,因为tuple已经被认为具有结构。这强调了元组是类和实例的轻量级选择。

#2


277  

Difference between list and tuple

列表和元组之间的差异。

  1. Literal

    文字

    someTuple = (1,2)
    someList  = [1,2] 
    
  2. Size

    大小

    a = tuple(range(1000))
    b = list(range(1000))
    
    a.__sizeof__() # 8024
    b.__sizeof__() # 9088
    

    Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements.

    由于一个tuple操作的规模较小,它会变得更快一些,但在您拥有大量元素之前并没有太多需要提及的内容。

  3. Permitted operations

    允许操作

    b    = [1,2]   
    b[0] = 3       # [3, 2]
    
    a    = (1,2)
    a[0] = 3       # Error
    

    That also means that you can't delete an element or sort a tuple. However, you could add new element to both list and tuple with the only difference that you will change id of the tuple by adding element

    这也意味着您不能删除一个元素或排序一个元组。但是,您可以将新元素添加到list和tuple中,只有通过添加元素来更改tuple的id。

    a     = (1,2)
    b     = [1,2]  
    
    id(a)          # 140230916716520
    id(b)          # 748527696
    
    a   += (3,)    # (1, 2, 3)
    b   += [3]     # [1, 2, 3]
    
    id(a)          # 140230916878160
    id(b)          # 748527696
    
  4. Usage

    使用

    As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used.

    由于列表是可变的,所以不能将它用作字典中的键,而可以使用元组。

    a    = (1,2)
    b    = [1,2] 
    
    c = {a: 1}     # OK
    c = {b: 1}     # Error
    

#3


166  

If you went for a walk, you could note your coordinates at any instant in an (x,y) tuple.

如果你去散步,你可以在一个(x,y)元组的任何瞬间记下你的坐标。

If you wanted to record your journey, you could append your location every few seconds to a list.

如果你想记录你的旅程,你可以每隔几秒就把你的位置添加到一个列表中。

But you couldn't do it the other way around.

但你不能反过来。

#4


65  

The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.

关键的区别在于元组是不可变的。这意味着,一旦创建了tuple,就不能更改它的值。

So if you're going to need to change the values use a List.

因此,如果需要更改值,请使用列表。

Benefits to tuples:

元组的好处:

  1. Slight performance improvement.
  2. 轻微的性能改进。
  3. As a tuple is immutable it can be used as a key in a dictionary.
  4. 作为一个元组是不可变的,它可以用作字典中的一个键。
  5. If you can't change it neither can anyone else, which is to say you don't need to worry about any API functions etc. changing your tuple without being asked.
  6. 如果你不能改变它,任何人都不能改变它,也就是说,你不需要担心任何API函数等等。

#5


27  

Lists are mutable; tuples are not.

列表是可变的;元组。

From docs.python.org/2/tutorial/datastructures.html

从docs.python.org/2/tutorial/datastructures.html

Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

元组是不可变的,通常包含通过解压缩访问的元素的异构序列(参见本节后面的部分)或索引(甚至在命名元组的情况下使用属性)。列表是可变的,它们的元素通常是同构的,并且通过迭代列表来访问它们。

#6


16  

Lists are for looping, tuples are for structures i.e. "%s %s" %tuple.

列表是用于循环的,元组是用于结构的。“% s % s %元组。

Lists are usually homogeneous, tuples are usually heterogeneous.

列表通常是同构的,元组通常是异构的。

Lists are for variable length, tuples are for fixed length.

列表为可变长度,元组为固定长度。

#7


14  

It's been mentioned that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline; some libraries actually behave differently based on what they are passed. Take NumPy for example (copied from another post where I ask for more examples):

有人提到,差异很大程度上是语义的:人们期望一个元组和一个列表来表示不同的信息。但这不仅仅是一个指南;一些库的行为实际上是基于它们所传递的内容。以NumPy为例(从我要求更多示例的另一篇文章中复制):

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

The point is, while NumPy may not be part of the standard library, it's a major Python library, and within NumPy lists and tuples are completely different things.

重点是,虽然NumPy可能不是标准库的一部分,但是它是一个主要的Python库,在NumPy列表和元组中是完全不同的东西。

#8


10  

This is an example of Python lists:

这是Python列表的一个示例:

my_list = [0,1,2,3,4]
top_rock_list = ["Bohemian Rhapsody","Kashmir","Sweet Emotion", "Fortunate Son"]

This is an example of Python tuple:

这是Python tuple的一个示例:

my_tuple = (a,b,c,d,e)
celebrity_tuple = ("John", "Wayne", 90210, "Actor", "Male", "Dead")

Python lists and tuples are similar in that they both are ordered collections of values. Besides the shallow difference that lists are created using brackets "[ ... , ... ]" and tuples using parentheses "( ... , ... )", the core technical "hard coded in Python syntax" difference between them is that the elements of a particular tuple are immutable whereas lists are mutable (...so only tuples are hashable and can be used as dictionary/hash keys!). This gives rise to differences in how they can or can't be used (enforced a priori by syntax) and differences in how people choose to use them (encouraged as 'best practices,' a posteriori, this is what smart programers do). The main difference a posteriori in differentiating when tuples are used versus when lists are used lies in what meaning people give to the order of elements.

Python列表和元组是相似的,因为它们都是有序的值集合。除了用括号“[……,……“和元组使用括号”(…,……)”,在Python语法中,核心技术“硬编码”的区别在于,特定元组的元素是不可变的,而列表是可变的(……)所以只有元组是可洗的,可以用作字典/散列键!这就产生了他们如何使用或不能使用的差异(由语法强制执行),以及人们如何选择使用它们(被鼓励为“最佳实践”,这是聪明的编程者所做的)。当使用元组时,当使用列表时,主要的区别是不同的,而使用列表时,人们给出的是元素的顺序。

For tuples, 'order' signifies nothing more than just a specific 'structure' for holding information. What values are found in the first field can easily be switched into the second field as each provides values across two different dimensions or scales. They provide answers to different types of questions and are typically of the form: for a given object/subject, what are its attributes? The object/subject stays constant, the attributes differ.

对于元组来说,“order”表示的只是一个特定的保存信息的“结构”。在第一个字段中找到的值可以很容易地转换为第二个字段,因为每个字段提供了跨两个不同维度或级别的值。它们为不同类型的问题提供答案,并且通常是形式:对于给定的对象/主题,它的属性是什么?对象/主题保持不变,属性不同。

For lists, 'order' signifies a sequence or a directionality. The second element MUST come after the first element because it's positioned in the 2nd place based on a particular and common scale or dimension. The elements are taken as a whole and mostly provide answers to a single question typically of the form, for a given attribute, how do these objects/subjects compare? The attribute stays constant, the object/subject differs.

对于列表,“order”表示序列或定向。第二个元素必须在第一个元素之后出现,因为它位于第2个位置,它基于一个特定的、通用的尺度或维度。这些元素被作为一个整体,并且主要是为一个单一的问题提供答案,对于一个给定的属性,这些对象/对象如何比较?属性保持不变,对象/主体不同。

There are countless examples of people in popular culture and programmers who don't conform to these differences and there are countless people who might use a salad fork for their main course. At the end of the day, it's fine and both can usually get the job done.

在流行文化和程序员中有无数不符合这些差异的例子,有无数的人可能会用一个沙拉叉作为主菜。在一天结束的时候,一切都很好,通常都能完成任务。

To summarize some of the finer details

来总结一些更精细的细节。

Similarities:

相似之处:

  1. Duplicates - Both tuples and lists allow for duplicates
  2. 副本——元组和列表都允许重复。
  3. Indexing, Selecting, & Slicing - Both tuples and lists index using integer values found within brackets. So, if you want the first 3 values of a given list or tuple, the syntax would be the same:

    索引、选择和切片-两个元组和列表索引使用括号内的整数值。因此,如果您想要给定列表或元组的前3个值,那么语法将是相同的:

    >>> my_list[0:3]
    [0,1,2]
    >>> my_tuple[0:3]
    [a,b,c]
    
  4. Comparing & Sorting - Two tuples or two lists are both compared by their first element, and if there is a tie, then by the second element, and so on. No further attention is paid to subsequent elements after earlier elements show a difference.

    比较和排序-两个元组或两个列表都比较它们的第一个元素,如果有一个tie,那么第二个元素,等等。在较早的元素显示出不同之后,对后续元素没有进一步的注意。

    >>> [0,2,0,0,0,0]>[0,0,0,0,0,500]
    True
    >>> (0,2,0,0,0,0)>(0,0,0,0,0,500)
    True
    

Differences: - A priori, by definition

区别:-根据定义,是先天的。

  1. Syntax - Lists use [], tuples use ()

    语法-列表使用[],元组使用()

  2. Mutability - Elements in a given list are mutable, elements in a given tuple are NOT mutable.

    一个给定列表中的元素是可变的,在给定的元组中元素不是可变的。

    # Lists are mutable:
    >>> top_rock_list
    ['Bohemian Rhapsody', 'Kashmir', 'Sweet Emotion', 'Fortunate Son']
    >>> top_rock_list[1]
    'Kashmir'
    >>> top_rock_list[1] = "Stairway to Heaven"
    >>> top_rock_list
    ['Bohemian Rhapsody', 'Stairway to Heaven', 'Sweet Emotion', 'Fortunate Son']
    
    # Tuples are NOT mutable:       
    >>> celebrity_tuple
    ('John', 'Wayne', 90210, 'Actor', 'Male', 'Dead')
    >>> celebrity_tuple[5]
    'Dead'
    >>> celebrity_tuple[5]="Alive"
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    
  3. Hashtables (Dictionaries) - As hashtables (dictionaries) require that its keys are hashable and therefore immutable, only tuples can act as dictionary keys, not lists.

    哈希表(字典)-作为哈希表(字典)要求它的键是可洗的,因此是不可变的,只有元组可以作为字典键,而不是列表。

    #Lists CAN'T act as keys for hashtables(dictionaries)
    >>> my_dict = {[a,b,c]:"some value"}
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    
    #Tuples CAN act as keys for hashtables(dictionaries)
    >>> my_dict = {("John","Wayne"): 90210}
    >>> my_dict
    {('John', 'Wayne'): 90210}
    

Differences - A posteriori, in usage

差异——在使用上是后验的。

  1. Homo vs. Heterogeneity of Elements - Generally list objects are homogenous and tuple objects are heterogeneous. That is, lists are used for objects/subjects of the same type (like all presidential candidates, or all songs, or all runners) whereas although it's not forced by), whereas tuples are more for heterogenous objects.

    元素的异质性——通常列表对象是同质的,而元组对象是异构的。也就是说,列表被用于相同类型的对象/主题(像所有的总统候选人,或者所有的歌曲,或者所有的跑步者),尽管它不是强制的,而元组更多的是针对异质对象。

  2. Looping vs. Structures - Although both allow for looping (for x in my_list...), it only really makes sense to do it for a list. Tuples are more appropriate for structuring and presenting information (%s %s residing in %s is an %s and presently %s % ("John","Wayne",90210, "Actor","Dead"))

    循环和结构——尽管两者都允许循环(对于my_list中的x来说…),但是对于一个列表来说,这样做是很有意义的。元组更适合于结构化和显示信息(%s %s在%s中存在%s,当前%s %(“John”,“Wayne”,90210,“Actor”,“Dead”))

#9


5  

Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures.

列表是同构序列,而元组是异构的数据结构。

#10


5  

The values of list can be changed any time but the values of tuples can't be change.

列表的值可以随时更改,但是元组的值不能更改。

The advantages and disadvantages depends upon the use. If you have such a data which you never want to change then you should have to use tuple, otherwise list is the best option.

优点和缺点取决于使用。如果您有这样的数据,您永远不想更改,那么您应该使用tuple,否则列表是最好的选择。

#11


1  

The PEP 484 -- Type Hints says that the types of elements of a tuple can be individually typed; so that you can say Tuple[str, int, float]; but a list, with List typing class can take only one type parameter: List[str], which hints that the difference of the 2 really is that the former is heterogeneous, whereas the latter intrinsically homogeneous.

PEP 484——类型提示说,元组的元素类型可以单独输入;所以你可以说Tuple[str, int, float];但是一个列表,有列表类型的类只能带一个类型参数:list [str],这暗示了2的区别实际上是前者是异构的,而后者是本质上是同质的。

Also, the standard library mostly uses the tuple as a return value from such standard functions where the C would return a struct.

另外,标准库主要使用元组作为从这些标准函数返回的值,其中C将返回一个struct。

#12


0  

First of all, they both are the non-scalar objects (also known as a compound objects) in Python.

首先,它们都是Python中的非标量对象(也称为复合对象)。

  • Tuples, ordered sequence of elements (which can contain any object with no aliasing issue)
    • Immutable (tuple, int, float, str)
    • 不可变(tuple, int, float, str)
    • Concatenation using + (brand new tuple will be created of course)
    • 使用+的连接(当然会创建全新的tuple)
    • Indexing
    • 索引
    • Slicing
    • 切片
    • Singleton (3,) # -> (3) instead of (3) # -> 3
    • 单例(3)# ->(3)而不是(3)# -> 3。
  • 元组,有序的元素序列(可以包含任何不存在混叠问题的对象)不可变(元组、整数、浮点数、str)连接使用+(当然,新的元组将被创建)索引切片单例(3)# ->(3)而不是(3)# -> 3。
  • List (Array in other languages), ordered sequence of values
    • Mutable
    • 可变的
    • Singleton [3]
    • 单例[3]
    • Cloning new_array = origin_array[:]
    • 克隆new_array = origin_array[:]
    • List comprehension [x**2 for x in range(1,7)] gives you [1,4,9,16,25,36] (Not readable)
    • 列表理解[x**2的范围(1,7)]给你[1,4,9,16,25,36](不可读)
  • 列表(数组在其他语言中),有序的值可变的单例序列[3]克隆new_array = origin_array[:]列表的理解[1,7)]给你[1,4,9,16,25,36](不可读)

Using list may also cause an aliasing bug (two distinct paths pointing to the same object).

使用列表还可能导致别名错误(指向同一对象的两个不同路径)。

#13


0  

A direction quotation from the documentation on 5.3. Tuples and Sequences:

一个方向报价从文档的5.3。元组和序列:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

虽然元组看起来类似于列表,但它们通常用于不同的情况和不同的目的。元组是不可变的,并且通常包含通过解包访问的异构元素序列(参见本节后面的部分)或索引(甚至在命名元组的情况下使用属性)。列表是可变的,它们的元素通常是同构的,并且通过迭代列表来访问它们。

#14


-1  

List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item.

列表是可变的,元组是不可变的。可变和不可变的主要区别是当您试图追加一个项目时的内存使用。

When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. E.g. if current memory assignment is 100 bytes, when you want to append the 101th byte, maybe another 100 bytes will be assigned (in total 200 bytes in this case).

当您创建一个变量时,一些固定的内存被分配给变量。如果它是一个列表,那么分配的内存比实际使用的要多。如果当前的内存分配是100个字节,当您想要追加101th字节时,可能会分配另外100个字节(在本例中总共为200个字节)。

However, if you know that you are not frequently add new elements, then you should use tuples. Tuples assigns exactly size of the memory needed, and hence saves memory, especially when you use large blocks of memory.

但是,如果您知道您不经常添加新元素,那么您应该使用元组。元组指定所需内存的大小,从而节省内存,特别是在使用大内存块时。

#15


-2  

Lists are mutable and tuples are immutable. Just consider this example.

列表是可变的,元组是不可变的。考虑一下这个例子。

a = ["1", "2", "ra", "sa"]    #list
b = ("1", "2", "ra", "sa")    #tuple

Now change index values of list and tuple.

现在更改列表和元组的索引值。

a[2] = 1000
print a     #output : ['1', '2', 1000, 'sa']
b[2] = 1000
print b     #output : TypeError: 'tuple' object does not support item assignment.

Hence proved the following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.

因此,证明下面的代码是无效的tuple,因为我们试图更新一个tuple,这是不允许的。

#1


848  

Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

除了元组是不可变的,还有一个语义区别,应该指导他们的使用。元组是异构的数据结构。,它们的条目有不同的含义,而列表是同质序列。元组有结构,列表有顺序。

Using this distinction makes code more explicit and understandable.

使用这种区分使代码更加清晰易懂。

One example would be pairs of page and line number to reference locations in a book, e.g.:

例如,在一本书中,一个例子是成对的页面和行号,例如:

my_location = (42, 11)  # page number, line number

You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.

然后,您可以将其用作字典中的键来存储位置的注释。另一方面,列表可以用来存储多个位置。很自然地,人们可能想要从列表中添加或删除位置,所以列表是可变的是有意义的。另一方面,从现有的位置添加或删除项是没有意义的,因此元组是不可变的。

There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.

在某些情况下,您希望在现有的位置元组中更改项目,例如在遍历页面的行时。但是tuple不变性迫使您为每个新值创建一个新的位置元组。这看起来很不方便,但是使用像这样的不可变数据是值类型和函数编程技术的基础,这可以有很大的优势。

There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this ("Tuples are immutable, and usually contain an heterogeneous sequence ...").

在这个问题上有一些有趣的文章。“Python元组不只是常量列表”或“理解Python中的元组和列表”。官方的Python文档也提到了这一点(“元组是不可变的,并且通常包含一个异构的序列…”)。

In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.

在像Haskell这样的静态类型语言中,元组中的值通常有不同的类型,并且元组的长度必须是固定的。在列表中,所有的值都具有相同的类型,并且长度不是固定的。差别非常明显。

Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.

最后是Python中的namedtuple,这是有意义的,因为tuple已经被认为具有结构。这强调了元组是类和实例的轻量级选择。

#2


277  

Difference between list and tuple

列表和元组之间的差异。

  1. Literal

    文字

    someTuple = (1,2)
    someList  = [1,2] 
    
  2. Size

    大小

    a = tuple(range(1000))
    b = list(range(1000))
    
    a.__sizeof__() # 8024
    b.__sizeof__() # 9088
    

    Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements.

    由于一个tuple操作的规模较小,它会变得更快一些,但在您拥有大量元素之前并没有太多需要提及的内容。

  3. Permitted operations

    允许操作

    b    = [1,2]   
    b[0] = 3       # [3, 2]
    
    a    = (1,2)
    a[0] = 3       # Error
    

    That also means that you can't delete an element or sort a tuple. However, you could add new element to both list and tuple with the only difference that you will change id of the tuple by adding element

    这也意味着您不能删除一个元素或排序一个元组。但是,您可以将新元素添加到list和tuple中,只有通过添加元素来更改tuple的id。

    a     = (1,2)
    b     = [1,2]  
    
    id(a)          # 140230916716520
    id(b)          # 748527696
    
    a   += (3,)    # (1, 2, 3)
    b   += [3]     # [1, 2, 3]
    
    id(a)          # 140230916878160
    id(b)          # 748527696
    
  4. Usage

    使用

    As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used.

    由于列表是可变的,所以不能将它用作字典中的键,而可以使用元组。

    a    = (1,2)
    b    = [1,2] 
    
    c = {a: 1}     # OK
    c = {b: 1}     # Error
    

#3


166  

If you went for a walk, you could note your coordinates at any instant in an (x,y) tuple.

如果你去散步,你可以在一个(x,y)元组的任何瞬间记下你的坐标。

If you wanted to record your journey, you could append your location every few seconds to a list.

如果你想记录你的旅程,你可以每隔几秒就把你的位置添加到一个列表中。

But you couldn't do it the other way around.

但你不能反过来。

#4


65  

The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.

关键的区别在于元组是不可变的。这意味着,一旦创建了tuple,就不能更改它的值。

So if you're going to need to change the values use a List.

因此,如果需要更改值,请使用列表。

Benefits to tuples:

元组的好处:

  1. Slight performance improvement.
  2. 轻微的性能改进。
  3. As a tuple is immutable it can be used as a key in a dictionary.
  4. 作为一个元组是不可变的,它可以用作字典中的一个键。
  5. If you can't change it neither can anyone else, which is to say you don't need to worry about any API functions etc. changing your tuple without being asked.
  6. 如果你不能改变它,任何人都不能改变它,也就是说,你不需要担心任何API函数等等。

#5


27  

Lists are mutable; tuples are not.

列表是可变的;元组。

From docs.python.org/2/tutorial/datastructures.html

从docs.python.org/2/tutorial/datastructures.html

Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

元组是不可变的,通常包含通过解压缩访问的元素的异构序列(参见本节后面的部分)或索引(甚至在命名元组的情况下使用属性)。列表是可变的,它们的元素通常是同构的,并且通过迭代列表来访问它们。

#6


16  

Lists are for looping, tuples are for structures i.e. "%s %s" %tuple.

列表是用于循环的,元组是用于结构的。“% s % s %元组。

Lists are usually homogeneous, tuples are usually heterogeneous.

列表通常是同构的,元组通常是异构的。

Lists are for variable length, tuples are for fixed length.

列表为可变长度,元组为固定长度。

#7


14  

It's been mentioned that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline; some libraries actually behave differently based on what they are passed. Take NumPy for example (copied from another post where I ask for more examples):

有人提到,差异很大程度上是语义的:人们期望一个元组和一个列表来表示不同的信息。但这不仅仅是一个指南;一些库的行为实际上是基于它们所传递的内容。以NumPy为例(从我要求更多示例的另一篇文章中复制):

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

The point is, while NumPy may not be part of the standard library, it's a major Python library, and within NumPy lists and tuples are completely different things.

重点是,虽然NumPy可能不是标准库的一部分,但是它是一个主要的Python库,在NumPy列表和元组中是完全不同的东西。

#8


10  

This is an example of Python lists:

这是Python列表的一个示例:

my_list = [0,1,2,3,4]
top_rock_list = ["Bohemian Rhapsody","Kashmir","Sweet Emotion", "Fortunate Son"]

This is an example of Python tuple:

这是Python tuple的一个示例:

my_tuple = (a,b,c,d,e)
celebrity_tuple = ("John", "Wayne", 90210, "Actor", "Male", "Dead")

Python lists and tuples are similar in that they both are ordered collections of values. Besides the shallow difference that lists are created using brackets "[ ... , ... ]" and tuples using parentheses "( ... , ... )", the core technical "hard coded in Python syntax" difference between them is that the elements of a particular tuple are immutable whereas lists are mutable (...so only tuples are hashable and can be used as dictionary/hash keys!). This gives rise to differences in how they can or can't be used (enforced a priori by syntax) and differences in how people choose to use them (encouraged as 'best practices,' a posteriori, this is what smart programers do). The main difference a posteriori in differentiating when tuples are used versus when lists are used lies in what meaning people give to the order of elements.

Python列表和元组是相似的,因为它们都是有序的值集合。除了用括号“[……,……“和元组使用括号”(…,……)”,在Python语法中,核心技术“硬编码”的区别在于,特定元组的元素是不可变的,而列表是可变的(……)所以只有元组是可洗的,可以用作字典/散列键!这就产生了他们如何使用或不能使用的差异(由语法强制执行),以及人们如何选择使用它们(被鼓励为“最佳实践”,这是聪明的编程者所做的)。当使用元组时,当使用列表时,主要的区别是不同的,而使用列表时,人们给出的是元素的顺序。

For tuples, 'order' signifies nothing more than just a specific 'structure' for holding information. What values are found in the first field can easily be switched into the second field as each provides values across two different dimensions or scales. They provide answers to different types of questions and are typically of the form: for a given object/subject, what are its attributes? The object/subject stays constant, the attributes differ.

对于元组来说,“order”表示的只是一个特定的保存信息的“结构”。在第一个字段中找到的值可以很容易地转换为第二个字段,因为每个字段提供了跨两个不同维度或级别的值。它们为不同类型的问题提供答案,并且通常是形式:对于给定的对象/主题,它的属性是什么?对象/主题保持不变,属性不同。

For lists, 'order' signifies a sequence or a directionality. The second element MUST come after the first element because it's positioned in the 2nd place based on a particular and common scale or dimension. The elements are taken as a whole and mostly provide answers to a single question typically of the form, for a given attribute, how do these objects/subjects compare? The attribute stays constant, the object/subject differs.

对于列表,“order”表示序列或定向。第二个元素必须在第一个元素之后出现,因为它位于第2个位置,它基于一个特定的、通用的尺度或维度。这些元素被作为一个整体,并且主要是为一个单一的问题提供答案,对于一个给定的属性,这些对象/对象如何比较?属性保持不变,对象/主体不同。

There are countless examples of people in popular culture and programmers who don't conform to these differences and there are countless people who might use a salad fork for their main course. At the end of the day, it's fine and both can usually get the job done.

在流行文化和程序员中有无数不符合这些差异的例子,有无数的人可能会用一个沙拉叉作为主菜。在一天结束的时候,一切都很好,通常都能完成任务。

To summarize some of the finer details

来总结一些更精细的细节。

Similarities:

相似之处:

  1. Duplicates - Both tuples and lists allow for duplicates
  2. 副本——元组和列表都允许重复。
  3. Indexing, Selecting, & Slicing - Both tuples and lists index using integer values found within brackets. So, if you want the first 3 values of a given list or tuple, the syntax would be the same:

    索引、选择和切片-两个元组和列表索引使用括号内的整数值。因此,如果您想要给定列表或元组的前3个值,那么语法将是相同的:

    >>> my_list[0:3]
    [0,1,2]
    >>> my_tuple[0:3]
    [a,b,c]
    
  4. Comparing & Sorting - Two tuples or two lists are both compared by their first element, and if there is a tie, then by the second element, and so on. No further attention is paid to subsequent elements after earlier elements show a difference.

    比较和排序-两个元组或两个列表都比较它们的第一个元素,如果有一个tie,那么第二个元素,等等。在较早的元素显示出不同之后,对后续元素没有进一步的注意。

    >>> [0,2,0,0,0,0]>[0,0,0,0,0,500]
    True
    >>> (0,2,0,0,0,0)>(0,0,0,0,0,500)
    True
    

Differences: - A priori, by definition

区别:-根据定义,是先天的。

  1. Syntax - Lists use [], tuples use ()

    语法-列表使用[],元组使用()

  2. Mutability - Elements in a given list are mutable, elements in a given tuple are NOT mutable.

    一个给定列表中的元素是可变的,在给定的元组中元素不是可变的。

    # Lists are mutable:
    >>> top_rock_list
    ['Bohemian Rhapsody', 'Kashmir', 'Sweet Emotion', 'Fortunate Son']
    >>> top_rock_list[1]
    'Kashmir'
    >>> top_rock_list[1] = "Stairway to Heaven"
    >>> top_rock_list
    ['Bohemian Rhapsody', 'Stairway to Heaven', 'Sweet Emotion', 'Fortunate Son']
    
    # Tuples are NOT mutable:       
    >>> celebrity_tuple
    ('John', 'Wayne', 90210, 'Actor', 'Male', 'Dead')
    >>> celebrity_tuple[5]
    'Dead'
    >>> celebrity_tuple[5]="Alive"
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    
  3. Hashtables (Dictionaries) - As hashtables (dictionaries) require that its keys are hashable and therefore immutable, only tuples can act as dictionary keys, not lists.

    哈希表(字典)-作为哈希表(字典)要求它的键是可洗的,因此是不可变的,只有元组可以作为字典键,而不是列表。

    #Lists CAN'T act as keys for hashtables(dictionaries)
    >>> my_dict = {[a,b,c]:"some value"}
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    
    #Tuples CAN act as keys for hashtables(dictionaries)
    >>> my_dict = {("John","Wayne"): 90210}
    >>> my_dict
    {('John', 'Wayne'): 90210}
    

Differences - A posteriori, in usage

差异——在使用上是后验的。

  1. Homo vs. Heterogeneity of Elements - Generally list objects are homogenous and tuple objects are heterogeneous. That is, lists are used for objects/subjects of the same type (like all presidential candidates, or all songs, or all runners) whereas although it's not forced by), whereas tuples are more for heterogenous objects.

    元素的异质性——通常列表对象是同质的,而元组对象是异构的。也就是说,列表被用于相同类型的对象/主题(像所有的总统候选人,或者所有的歌曲,或者所有的跑步者),尽管它不是强制的,而元组更多的是针对异质对象。

  2. Looping vs. Structures - Although both allow for looping (for x in my_list...), it only really makes sense to do it for a list. Tuples are more appropriate for structuring and presenting information (%s %s residing in %s is an %s and presently %s % ("John","Wayne",90210, "Actor","Dead"))

    循环和结构——尽管两者都允许循环(对于my_list中的x来说…),但是对于一个列表来说,这样做是很有意义的。元组更适合于结构化和显示信息(%s %s在%s中存在%s,当前%s %(“John”,“Wayne”,90210,“Actor”,“Dead”))

#9


5  

Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures.

列表是同构序列,而元组是异构的数据结构。

#10


5  

The values of list can be changed any time but the values of tuples can't be change.

列表的值可以随时更改,但是元组的值不能更改。

The advantages and disadvantages depends upon the use. If you have such a data which you never want to change then you should have to use tuple, otherwise list is the best option.

优点和缺点取决于使用。如果您有这样的数据,您永远不想更改,那么您应该使用tuple,否则列表是最好的选择。

#11


1  

The PEP 484 -- Type Hints says that the types of elements of a tuple can be individually typed; so that you can say Tuple[str, int, float]; but a list, with List typing class can take only one type parameter: List[str], which hints that the difference of the 2 really is that the former is heterogeneous, whereas the latter intrinsically homogeneous.

PEP 484——类型提示说,元组的元素类型可以单独输入;所以你可以说Tuple[str, int, float];但是一个列表,有列表类型的类只能带一个类型参数:list [str],这暗示了2的区别实际上是前者是异构的,而后者是本质上是同质的。

Also, the standard library mostly uses the tuple as a return value from such standard functions where the C would return a struct.

另外,标准库主要使用元组作为从这些标准函数返回的值,其中C将返回一个struct。

#12


0  

First of all, they both are the non-scalar objects (also known as a compound objects) in Python.

首先,它们都是Python中的非标量对象(也称为复合对象)。

  • Tuples, ordered sequence of elements (which can contain any object with no aliasing issue)
    • Immutable (tuple, int, float, str)
    • 不可变(tuple, int, float, str)
    • Concatenation using + (brand new tuple will be created of course)
    • 使用+的连接(当然会创建全新的tuple)
    • Indexing
    • 索引
    • Slicing
    • 切片
    • Singleton (3,) # -> (3) instead of (3) # -> 3
    • 单例(3)# ->(3)而不是(3)# -> 3。
  • 元组,有序的元素序列(可以包含任何不存在混叠问题的对象)不可变(元组、整数、浮点数、str)连接使用+(当然,新的元组将被创建)索引切片单例(3)# ->(3)而不是(3)# -> 3。
  • List (Array in other languages), ordered sequence of values
    • Mutable
    • 可变的
    • Singleton [3]
    • 单例[3]
    • Cloning new_array = origin_array[:]
    • 克隆new_array = origin_array[:]
    • List comprehension [x**2 for x in range(1,7)] gives you [1,4,9,16,25,36] (Not readable)
    • 列表理解[x**2的范围(1,7)]给你[1,4,9,16,25,36](不可读)
  • 列表(数组在其他语言中),有序的值可变的单例序列[3]克隆new_array = origin_array[:]列表的理解[1,7)]给你[1,4,9,16,25,36](不可读)

Using list may also cause an aliasing bug (two distinct paths pointing to the same object).

使用列表还可能导致别名错误(指向同一对象的两个不同路径)。

#13


0  

A direction quotation from the documentation on 5.3. Tuples and Sequences:

一个方向报价从文档的5.3。元组和序列:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

虽然元组看起来类似于列表,但它们通常用于不同的情况和不同的目的。元组是不可变的,并且通常包含通过解包访问的异构元素序列(参见本节后面的部分)或索引(甚至在命名元组的情况下使用属性)。列表是可变的,它们的元素通常是同构的,并且通过迭代列表来访问它们。

#14


-1  

List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item.

列表是可变的,元组是不可变的。可变和不可变的主要区别是当您试图追加一个项目时的内存使用。

When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. E.g. if current memory assignment is 100 bytes, when you want to append the 101th byte, maybe another 100 bytes will be assigned (in total 200 bytes in this case).

当您创建一个变量时,一些固定的内存被分配给变量。如果它是一个列表,那么分配的内存比实际使用的要多。如果当前的内存分配是100个字节,当您想要追加101th字节时,可能会分配另外100个字节(在本例中总共为200个字节)。

However, if you know that you are not frequently add new elements, then you should use tuples. Tuples assigns exactly size of the memory needed, and hence saves memory, especially when you use large blocks of memory.

但是,如果您知道您不经常添加新元素,那么您应该使用元组。元组指定所需内存的大小,从而节省内存,特别是在使用大内存块时。

#15


-2  

Lists are mutable and tuples are immutable. Just consider this example.

列表是可变的,元组是不可变的。考虑一下这个例子。

a = ["1", "2", "ra", "sa"]    #list
b = ("1", "2", "ra", "sa")    #tuple

Now change index values of list and tuple.

现在更改列表和元组的索引值。

a[2] = 1000
print a     #output : ['1', '2', 1000, 'sa']
b[2] = 1000
print b     #output : TypeError: 'tuple' object does not support item assignment.

Hence proved the following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.

因此,证明下面的代码是无效的tuple,因为我们试图更新一个tuple,这是不允许的。