0

This is my first question here. I just started coding in Python, and trying to finish an assignment for my study in Python (it is actually supposed to be made in STATA but I want to learn Python).

So I want to do the following (note that the final_list consists of 15000 rows, this is just a small example):

final_list = [[2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 516.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 517.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 518.0, 0.0, 0.0, 0.0, 2003.0]

to

treshold = [11.0, 11.0, 11.0]

Now what I've tried is this:

treshold = []
for sublist in final_list:
    treshold_lst = sublist[3]
    treshold.append(treshold_lst)
print(treshold)

I receive the following error:

IndexError: list index out of range

Does anyone see what I'm doing wrong?

8
  • 3
    I don't see any error in your code repl.it/repls/OilyResponsibleBaboon Commented Nov 14, 2017 at 9:25
  • are you sure that final_list looks like that? Commented Nov 14, 2017 at 9:26
  • 1
    Can't reproduce. Commented Nov 14, 2017 at 9:26
  • The final_list you've posted now is invalid. The problem obviously lies with that list, not with the logic you've posted. Commented Nov 14, 2017 at 9:30
  • Have you just changed your code? Commented Nov 14, 2017 at 9:32

1 Answer 1

2

Try list comprehension:

final_list = [[1,2,3,4],[1,2,3,5],[1,3,4,6]]
treshold = [sub[-1] for sub in final_list]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.