2

I have a list l = [1, 2, 3] and I want l[2->infinity] == 3. It would essentially look like [1, 2, 3, 3, 3, 3, ...]. I tried:

[1, 2, *3]

or

[1, 2, 3, ...]

Is there anyway to add a "default element" for a range of indices?

Clarification

I don't want to repeat the element n times because I can't index outside the length of the list. I want to actually have a value for all indexes from 2->infinity. Some sort of default value for that index range.

Harry Stuart
  • 1,781
  • 2
  • 24
  • 39
  • Python lists are finite. We're not Haskell here. – user2357112 Apr 19 '19 at 06:03
  • 1
    Nominating this question for reopening because of the clarification. I think the actual answer to Harry's question is to override `__getitem__` (I think the question's details make it unique enough, but if it's a duplicate, then it's a duplicate of https://stackoverflow.com/questions/1957780/how-to-override-the-operator-in-python) – Chris Martin Apr 19 '19 at 19:50
  • Agreed. It wasn't obvious from the title of the question, but when the OP asked for "add[ing] a 'default element' for a range of indices" then yes it's clear that `__getitem__` is the way to go. That would be a better way to get `a[1000000]` efficiently for sure. – Ray Toal Apr 19 '19 at 19:56

2 Answers2

8

The best way I can think of is to chain two iterators together, like so:

from itertools import *

chain([1, 2], repeat(3))

REPL example:

>>> list(islice(chain([1, 2], repeat(3)), 10))
[1, 2, 3, 3, 3, 3, 3, 3, 3, 3]
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
2

Alternatively to Chris answer, you can create your own generator:

def inf3():
    yield 1
    yield 2
    while True:
        yield 3

>>> g = inf3()
>>> [next(g) for _ in range(100)]
[1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
Netwave
  • 40,134
  • 6
  • 50
  • 93