-1

This function:

def assisted_by(self, players):
    text = self.event_text.split('Assisted')
    if len(text) > 1:
       print ([i for i in players if i in text[1]])
       return [i for i in players if i in text[1]][0]
    else:
       return 'N/A'

prints hundreds of items and ends up with an empty list:

(...)

['Kelechi Iheanacho']
['James Maddison']
['Wilfried Zaha']
['Emiliano Buendia']
[]

Returning the following error:

  File "data_gathering.py", line 1057, in assisted_by
    return [i for i in players if i in text[1]][0]
IndexError: list index out of range

How can I fix this error without removing [0] index?

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198
  • The list is empty.... what you do want to return in that case? – tdelaney May 01 '20 at 01:34
  • What is `text`? If you have an empty list then there is no `[0]` index. If it's not certain that the index exist you should be checking that before accessing it. See: [mcve](https://stackoverflow.com/help/minimal-reproducible-example) – Spencer Wieczorek May 01 '20 at 01:43
  • Does this answer your question? [How do I check if a list is empty?](https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty) – Spencer Wieczorek May 01 '20 at 01:45

1 Answers1

0

You can't get item 0 from an empty list. You could check length before you try:

def assisted_by(self, players):
    text = self.event_text.split('Assisted')
    if len(text) > 1:
        data = [i for i in players if i in text[1]]
        print(data)
        if data:
            return data[0]
    return 'N/A'

~

tdelaney
  • 73,364
  • 6
  • 83
  • 116