Difference between list, sequence and slice in Python?

Tony the Pony picture Tony the Pony · May 27, 2010 · Viewed 29.9k times · Source

What are the differences between these built-in Python data types: list, sequence and slice? As I see it, all three essentially represent what C++ and Java call array.

Answer

Jochen Ritzel picture Jochen Ritzel · May 27, 2010

You're mixing very different things in your question, so I'll just answer a different question ;-P

You are now asking about one of the most important interface in Python: iterable - it's basically anything you can use like for elem in iterable.

iterable has three descendants: sequence, generator and mapping.

  • A sequence is a iterable with random access. You can ask for any item of the sequence without having to consume the items before it. With this property you can build slices, which give you more than one element at once. A slice can give you a subsequence: seq[from:until] and every nth item: seq[from:until:nth]. list, tuple and str all are sequences.

  • If the access is done via keys instead of integer positions, you have a mapping. dict is the basic mapping.

  • The most basic iterable is a generator. It supports no random access and therefore no slicing. You have to consume all items in the order they are given. Generator typically only create their items when you iterate over them. The common way to create generators are generator expressions. They look exactly like list comprehension, except with round brackets, for example (f(x) for x in y). Calling a function that uses the yield keyword returns a generator too.

The common adapter to all iterables is the iterator. iterators have the same interface as the most basic type they support, a generator. They are created explicitly by calling iter on a iterable and are used implicitly in all kinds of looping constructs.