Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list, sequence and slice in Python?

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.

like image 983
Tony the Pony Avatar asked May 27 '10 11:05

Tony the Pony


People also ask

Is a list a sequence Python?

Python has the following built-in sequence types: lists, bytearrays, strings, tuples, range, and bytes.

Is a list a sequence?

Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in list are called elements or sometimes items.

How do you slice a sequence in Python?

Python slice() Function The slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

What are the six types of sequences in Python?

Python supports six different types of sequences. These are strings, lists, tuples, byte sequences, byte arrays, and range objects.


1 Answers

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

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.

like image 172
Jochen Ritzel Avatar answered Oct 18 '22 08:10

Jochen Ritzel