What is the difference between lists and tuples in Python?
开发者_Go百科Which is more efficient? What is the typical use of each?
Lists are mutable sequences, with lots and lots of methods (both mutating and non-mutating ones), that are most often used as general purpose containers (their items can be objects of any types at all, although it's sometimes considered better style for lists to have items that are of the same type or types to be used equivalently).
Tuples are immutable sequences, with very few methods (all non-mutating special ones), that are most often used when you need immutability for the purpose of using a container as an item in a set or a key in a dict (though the items will also have to be immutables -- e.g. strings, numbers, or other nested tuples, for this to work). Their items can be objects of any types at all and it's perfectly normal for tuples to have items of many different and distinct types.
There are a few cases in which either a tuple or a list would serve just as well, and in such few cases the fact that tuples are a bit smaller and faster to build can be used to sway the decision in favor of tuples. For example, when a function needs to return multiple results, it's most normal to use
return fee, fie, foo, fum
i.e., return a tuple with the four items in question, rather than
return [fee, fie, foo, fum]
i.e., return a list with the four items -- besides (small gains in) performance, the "return a tuple" common idiom also deals with the issue that often the multiple results being returned are not of the same nor interchangeable types, so, stylistically speaking, using a list might be considered a more dubious choice anyway.
A useful variant of tuple
is its sub-type collections.namedtuple (requires Python 2.6 or better) which lets you access items by name (with attribute syntax) as well as by index (the normal way). For example, with an import collections
at the top of the module, the above return
statement might become...
freturn = collections.namedtuple('freturn', 'fee fie foo fum')
def f():
...
return freturn(fee, fie, foo, fum)
Now, the caller of f()
could use its return value as a tuple, just as before, but would gain nice alternatives such as...:
r = f()
print r.fie
in lieu of the less immediately clear and readable
print r[1]
It's important to note that a named tuple subclass made with collections.namedtuple
has essentially no extra overhead compared with using a tuple directly, or, as the docs put it,
they are lightweight and require no more memory than regular tuples.
A list is mutable, you can add elements to it. A tuple isn't, which means it's (slightly) more efficient. Tuples are also hashable, so can be used as e.g. the key in a dictionary.
Read this.
Lists are mutable (can be changed), tuples are immutable. Typical use: it sounds rather trite but you use lists when you need to change the values. Tuples are generally a little more efficient because of their immutability (unless you are using them like lists and duplicating them a lot...)
After some reading of Python doc. on Built-in types, I created the below table to show the main differences among the six iterable containers.
<pre>
Container Notation Index [n:m] Mutable Hashable
========= ========== =========== ======= ========
String ' ' or " " position Immutable Yes
Range range(,,) position Immutable Yes
Tuple (,) position Immutable Yes
List [,] position Yes No
Set {,} No Yes No
Dict {k:v,k:v} by key Yes No
</pre>
Search is faster for set and dict because they are hashed instead of sequenced and thus independent of size. Tuple and list are same except tuple is immutable with fewer methods than list, thus it doesn't support item assignment to alter its content. But two tuples can be concatenated to achieve "append" functionality, i.e. t1 += t2
.
Since only immutable sequence types support hash(), list, set and dict cannot be used as a dict key. This can be easily seen below where 'a' is a dict sequence which contains hetero immutable key types of int, float, str, range and tuple:
>>> a
{range(2, 5, 2): 'range', 3: 15, 4.5: 16, 'llmjxm': 'c', -555: 666, -4.5: -25, (5, 6, 7): 'blue', 'abc3': 215, (1, 2, 3): 'red'}
>>> for item in a.keys():
... print(item, '\t\t==>>', a[item])
...
range(2, 5, 2) ==>> range
3 ==>> 15
4.5 ==>> 16
llmjxm ==>> c
-555 ==>> 666
-4.5 ==>> -25
(5, 6, 7) ==>> blue
abc3 ==>> 215
(1, 2, 3) ==>> red
>>>
whereas a key of mutable type will result in TypeError:
>>> a[{5}] = 56
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> a[[5]] = 56
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> a[{5:6}] = 56
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> a[-555] = 666
>>>
Refer to link1 and link2 for more details.
精彩评论