-1

For a small test I am doing, I need to print the 5th element of a list, if there is one.

with open (my_file, 'r') as my_probe:
    for fileLine in my_probe:
        src_string = fileLine.split()
        my_list = list(src_string) # The list may contain any number of items
        if len(my_list) > 3: # Only if lists is longer than 4 items
            print("Info I need: "+my_list[4])

When I run the code, however, it nevertheless tries to print the 5th element of lists with less then 5 elements and thus returns an error showing I am trying to print unexisting item:

Traceback (most recent call last):
  File "my_script.py", line 70, in <module>
    print ("Info I need: "+my_list[4])
IndexError: list index out of range

Could anyone suggests a way to overcome this problem?

Thanks in advance!

Asenski
  • 49
  • 1
  • 1
  • 8
  • 2
    `my_list[4]` is the fifth element of `my_list`. Python indices start from `0`. Also `len(my_list) > 3:` does not mean `# Only if lists is longer than 4 items`, it means `# Only if lists is longer than 3 items`. – dROOOze Mar 28 '18 at 16:32
  • 2
    Use a try/except? – user3483203 Mar 28 '18 at 16:33
  • 1
    If you want to print the 5th element, the length of the list has to be greater than 4, not 3... – Thierry Lathuille Mar 28 '18 at 16:34
  • I am not certain how to go about the the try / except approach but changing the if condition solved the problem. – Asenski Mar 28 '18 at 16:39

2 Answers2

1
with open (my_file) as my_probe:
    for fileLine in my_probe:
        src_string = fileLine.split()
        my_list = list(src_string) # The list may contain any number of items
        if len(my_list) >= 5: # Only if lists is longer than 4 items
            print("Info I need: "+my_list[4])

Note down the list index starts with 0 however length is the count of actual element in that list.

MaNKuR
  • 2,578
  • 1
  • 19
  • 31
  • Thank you! Yes, in deed, it's been a brain freeze from my end. It would make absolutely no sense to say a list with 1 item has length of 0 despite the first item being counted as position 0 (my_list[0]), as this puts the question what would be given as length for lists with no items. I spent so much time trying to figure out what I am doing wrong and it was the most obvious thing! – Asenski Mar 28 '18 at 16:42
0

First one there is no string named my_string in your code. Other Problem is you are accessing the 5th element of list which has length of 3. so you have change your if statement to if len(my_list)>=5.

 with open (my_file, 'r') as my_probe:
    for fileLine in my_probe:
        src_string = fileLine.split()
        my_list = list(src_string) # The list may contain any number of items
        if len(my_list) >= 5: # Only if lists is longer than 4 items
            print(my_list[4])
py-D
  • 661
  • 5
  • 8