Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is any Python type whose objects contain elements that are numbered called a sequence type?

Tags:

python

I've been confused about that question for a long time. Is any Python type whose objects contain elements that are numbered called a sequence type?

like image 341
Guanfang Dong Avatar asked Mar 06 '26 00:03

Guanfang Dong


1 Answers

A sequence is a type that follows the sequence protocol. That implies not just that indices are numeric, but that they are consecutive, start at zero, and iterating yields elements in order of increasing index, and that len(my_sequence) works. In practice, this means they need to implement __getitem__ and __len__ methods appropriately. From there, Python can "fill in the blanks" so that iteration, x in my_sequence and reversed(my_sequence) all work without implementing the associated methods - but they might still choose to implement those, particularly if they can provide a more efficient implementation (for example, the default iteration behaviour is as if __iter__ just tried self[i] from i=0 until it hits an IndexError, which isn't ideal for a linked list).

like image 125
lvc Avatar answered Mar 07 '26 15:03

lvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!