Skip to content

Specs: lists in Python §3 and §4 #299

Description

@martin-henz

Lists in Python behave differently than JavaScript arrays. In Python §3 and §4, the following behavior is expected:

Index range for list access and list assignment

The range of indices allowed for accessing/assigning to a Python list my_list is -len(my_list) to len(my_list) - 1.

  • Any other integer index gives IndexError: list index out of range, e.g. [1,2] [2]
  • Any index other than integers gives TypeError: list indices must be integers, e.g. [1,2] [0.0]
  • As opposed to Python, Python §3 and §4 does not allow boolean values as indices, e.g. [1,2] [True] gives TypeError: list indices must be integers
  • As in Python and as opposed to JavaScript's array assignment, list assignment in Python §3 and §4 does not automatically extend the data structure: [0,0] [2] = 5 gives IndexError: list assignment index out of range.
  • As in Python, the indices wrap around for negative indices -len(my_list) to -1: if my_list[i] gives a value, then my_list[i % len(my_list)] gives the same value.

List multiplication

Source did not provide an array constructor, relying on JavaScript's automatic extension of arrays. We do not have (iterable) objects in Python §3 and §4, so Python's list constructor is not an option. Instead, we use Python's multiplication my_list * 5 and 5 * my_list with one operand a list and the other an integer as a reasonably Pythonic generic list constructor. If the integer is 0 or less, the result is [], and for a positive integer i, the result is the list duplicated i times.

Boolean operands of * are not allowed.

Error messages:

  • [1,2] * 0.0: TypeError: can't multiply list by non-integer
  • 0.0 * [1,2]: TypeError: can't multiply list by non-integer
  • True * [1,2]: TypeError: can't multiply list by non-integer
  • [1,2] * True: TypeError: can't multiply list by non-integer

As in real Python, multiplication makes shallow copies:

x = [[1,2]] * 4
print(x[0] is x[1]) # prints True

Fixes #294

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions