-1

Does anyone know why this code wouldnt work if there was hypothetically an empty list. When I run a test for the empty list it give me indexerror that it is out of range.

def dedup(l):
    dl = [l[0]]
    for v in l[1:]:
     if dl[-1] != v:
      dl.append(v)
    return dl 
kimberly
  • 17
  • 2
  • An empty list can not be sliced and elements can not be retrieved, because.... the list is "empty" – stuckoverflow May 01 '21 at 19:39
  • 1
    Does this answer your question? [python : list index out of range error while iteratively popping elements](https://stackoverflow.com/questions/1798796/python-list-index-out-of-range-error-while-iteratively-popping-elements) – stuckoverflow May 01 '21 at 19:42

4 Answers4

0

If the list is empty, l[0] does not exist (there is no first element).

You can add an explicit check for that.

dl = [l[0]] if l else []

# or

if not l: return l
dl = [l[0]]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

This is because in an empty list how can you access the elements using index as there are no elements in it.

When you use l[0] the first element will be accessed. But in an empty list there is no first element. Hence the reason for the error

12081
  • 21
  • 5
0

You need to check whether the import array is empty or not

if len(l) != 0:
top talent
  • 615
  • 4
  • 17
0

I'd test for the case when there is either 0 or 1 and return as well.

ETA: of course list(set()) also works.

def dedup(l):
    if len(l) < 2:
        return l
    dl = [l[0]]
    for v in l[1:]:
        if dl[-1] != v:
            dl.append(v)
    return dl

print(dedup([1, 1, 11, 3]))
print(dedup([]))

print(list(set([1, 1, 11, 3])))
print(list(set([])))
jwal
  • 630
  • 6
  • 16