Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why implement two so similar data structures like List and Tuple [duplicate]

In python, the list data structure is a sequence of elements. Similarly, a tuple is also a sequence of elements, however, tuples are immutable.

Whats the reason for making such a similar data structure, thats only feature, as opposed to lists, is that it can't be changed? Does it perhaps save memory space, by being immutable?

Also if a list and a tuple contains the exact same data, will they use the same amount of space in the memory?

like image 954
Daniel Mac Avatar asked Sep 19 '13 13:09

Daniel Mac


People also ask

What is an advantage of using a tuple over a list?

The advantages of tuples over the lists are as follows: Tuples are faster than lists. Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in 'tuples' than in 'list'.

Can list and tuple have duplicate values?

Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members. Sets Sets are a collection that is unordered and unindexed. They are mutable (changeable) but do not allow duplicate values to be held.

What are two reasons why tuples exist in Python?

Advantages of Tuples in Python over Lists Following are some of the main advantages: Iteration in a tuple is faster as compared to lists since tuples in Python are immutable. Tuples are generally used for different Python Data Types; whereas, lists are used for similar data types.


1 Answers

Immutable types are hashable, and can be used as dictionary keys. This works:

key = (1, 2, 3)
d = {key: 1}

But this doesn't:

key = [1, 2, 3]
d = {key: 1}

If it did, what would you expect this to do?

key[0] = 2
print d[key]        # id(key) hasn't changed, so surely the lookup should still work
print d[[1, 2, 3]]  # but also, we stored a piece of data at [1, 2, 3], didn't we?
print d[[2, 2, 3]]  # but if d[key] works, surely we can expand key to its value
like image 100
Eric Avatar answered Sep 26 '22 16:09

Eric