What's the Difference Between Lists and Tuples

What's the difference between lists and tuples?

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.

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 ...".

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.

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.

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

Is there a difference between a list and a tuple?

A tuple is just a finite list. All tuples are lists. All finite lists are tuples. Infinite lists are not tuples. All differences of typing and semantics are purely language dependent considerations.

What is the difference between a list, a tuple and an array as data structures?

Talking about "arrays" and "lists" as abstract data types without referring to any particular implementation can be a bit confusing, because those two are not very well defined.

The two Wikipedia pages List (abstract data type) and Array data type make this ambiguity somewhat evident, with uncertain statements such as "Implementation of the list data structure may provide some of the following operations:".

In many languages, there is a type called list and a type called array and they have some better defined meaning.

Here is a very general summary.

Lists:

  • a list is linear, it is an ordered sequence of elements;
  • you can access the first element of a list;
  • you can add a new element to a list;
  • you can access all elements of the list one after the other, starting from the first element.
    That last operation is done either with "arbitrary access" (accessing elements as l[0], l[1], l[2], etc.) or with two operations called "head" and "tail", where head(l) returns the first element of l and tail(l) returns the sublist obtained by discarding the first element.

In my mind, a list of four elements looks like this:

-> 3 -> 7 -> 12 -> 9

Arrays:

  • an array provides "arbitrary access" using indices (accessing elements as a[something]);
  • sometimes the index is restricted to integers between 0 and the length of the array; sometimes the index can be anything and everything;
  • you can easily modify elements that you access, but you cannot necessarily add new elements.

An array which allows anything to be used as index is usually called a map or a dict in most languages, where array refers strictly to linear structures indexed by integers; but in a few languages, for instance PHP, it is still called an array.

In my mind, an array of four elements looks like this:

+--+--+--+--+
| 0| 1| 2| 3|
+--+--+--+--+
| 3| 7|12| 9|
+--+--+--+--+

Tuples:

  • a linear, ordered sequence of elements;
  • usually can contain elements of different types, whereas in most languages, all the elements in a list must have the same type;
  • usually cannot add/remove elements
  • in strongly-typed languages, such as Haskell or OCaml, the type of a tuple is given by its length and the enumeration of the types used in it, for instance the tuple (3, 7, 12.0, "9") has type (int, int, float, string), and a function returning a specific type of tuple cannot suddenly return a tuple of a different type.

Tuples in strongly-typed languages are sometimes called "product types" by analogy with the Cartesian product in mathematics, and are very close to struct in C. Tuples in weakly-typed languages are very close to lists.

What is the difference between Tuple, Dictionary and List in C#?

First, AFAIK, there isn't any list that takes two type parameters - so your List could either be a List<int> or List<string> (or a SortedList<int,string>, but that's a different class).

A Tuple<T1, T2> holds two values - one int and one string in this case. You can use a Tuple to bind together items (that might be of different
types). This may be useful in many situations, like, for instance, you want to return more than one value from a method.

I personally hate the Item1, Item2 property names, so I would probably use a wrapper class around Tuples in my code.

A Dictionary<TKey, TValue> is a collection of KeyValuePair<TKey, TValue>. A Dictionary maps keys to values, so that you can have, for instance, a dictionary of people and for each person have their SSN as a key.

A List<T> is a collection of T.
You can get individual items by using the index, the Find method, or simply LINQ (since it implements IEnumerable<T>).

What is the difference between lists and tuples in Python?

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.

What is the difference between lists,tuples,sets and dictionaries?

A list is a sequence of elements in a specific order. You can access elements with a numerical index, e.g. the_list[3]. The time taken for several operations such as testing if the list contains an element is O(n), i.e. proportional to the length of the list.

A tuple is basically an immutable list, meaning you can't add, remove, or replace any elements.

A set has no order, but has the advantage over a list that testing if the set contains an element is much faster, almost regardless of the size of the set. It also has some handy operations such as union and intersection.

A dictionary is a mapping from keys to values where the keys can be all sorts of different objects, in contrast to lists where the 'keys' can only be numbers. So you can have the_dict = {'abc': 3, 'def': 8} and then the_dict['abc'] is 3. They keys of a dict are much like a set: they have no order and you can test for their existence quickly.

The elements of a set and the keys of a dict must be hashable. Numbers, strings, tuples, and many other things are hashable. Lists, sets, and dicts are not hashable.

Difference between tuples in list of tuples

You can do something like:

any(tup for tup in list_tup if tup[0] == '123' and tup[1] != 'B')

Basically filters the list of tuples to those that have '123' as the first value and not 'B' as the second value, and returns True if there are any (haha).

But you can also modify this to get the list of all tuples that match the criteria by switching any to list.

Difference between list and tuple (minus immutability) in Python?

Both lists and tuples are internally implemented as arrays of references to the element objects. This way, both can be indexed and both require the same amount of memory for each element. Internally, they are both homogeneous (untyped references). Logically, they are both heterogeneous (automatic dereferencing, the type is bound to the target object).

The list can be modified, so the internal array is a dynamic array. The tuple cannot be modified, so it is internally just fixed-size array. From that point of view, tuples are simpler.

For which is faster or not, you can measure the concrete situation using the timeit module.

You should be aware of the fact that tuples are immutable only with respect to the number and to values of the stored references. If (say) a list is used as one of the tuple elements, the list content can be changed. This way, logically, the tuple content is not constant (such tuple is not hashable).

Use whatever type is better for the purpose. There is no strict preference. It depends on the situation.



Related Topics



Leave a reply



Submit