0

I have data of the following form:

list_of_numbers = [[8, 10], [10, 8, 1, 0], [6], [4, 0, 1, 2, 3], [12]]

I am trying to extract the first and second element of this list as follows:

[n[0] for n in list_of_numbers]

This works well for the first element, however, when I try to extract the second element in the same way I get an error (IndexError: list index out of range). I realise this is because the some of the lists in the list do not have a second element. However, I need to extract the second element whenever it exists, and have NaN/missing when it doesn't. How do I go about implementing this in my code?

Thanks!

Amy D
  • 55
  • 1
  • 6
  • Possible duplicate of [I want to exception handle 'list index out of range.'](https://stackoverflow.com/questions/11902458/i-want-to-exception-handle-list-index-out-of-range) – pault Oct 01 '19 at 16:42

2 Answers2

2

You could use a conditional list comprehension to check the length of the inner lists and index them only if they are above a certain length:

index = 1
[i[index] if len(i)>index else float('nan') for i in list_of_numbers]
# [10, 8, nan, 0, nan]
yatu
  • 86,083
  • 12
  • 84
  • 139
0

This solution puts None when the list is not long enough. You can replace it with whatever you like (e.g. np.nan).

Solution:

i = 1
[None if len(n) <= i else n[i] for n in list_of_numbers]

Result:

[10, 8, None, 0, None]
brentertainer
  • 2,118
  • 1
  • 6
  • 15