[Tutor] Index Out of Range?List

Alan Gauld alan.gauld at yahoo.co.uk
Wed May 3 20:51:41 EDT 2017


On 04/05/17 00:32, Stephen P. Molnar wrote:

> import numpy as np
> 
> name = input("Enter Molecule ID: ")
> name = str(name)

You don't need the str(), input always returns a string.

> name_in =name[:]+'.lac.dat'

And you don't need the [:]. Just use

name_in = name + '.lac.dat'

> print(name_in)
> 
> atm_chg = []

> """
> atm_chg = open(name_in,'r')
> for line in atm_chg:
>      print(line, end=' ')
> """
This creates a 3 line string which is not assigned to any object.
It is not executable code and will not be executed. Maybe you
are doing it as a way of commenting out a block? If so it would be
better in a post to just delete it, it just adds confusion
otherwise. (Well, it confused me! :-)

> with open(name_in) as f:
>      # skip two lines
>      f.readline()
>      f.readline()
>      for line in f.readlines():
>          atm_chg.append(float( line.split()[-1] ))
> 
> p.asarray({atm_chg})

Where did p come from?
Should it be np? asarray() sounds like it might be a numpy thing.
And I'm not sure what the {atm_chg} is supposed to do - create
a single element set using your list maybe? I get an "unhashable"
error if I try it at the >>>> prompt.

> When it is run I get:
> 
> IndexError: list index out of range

I'm pretty sure you get more than that, please post the full
error text, it's much harder to diagnose problems with just
the summary.

Since the only indexing you do is in this line

>          atm_chg.append(float( line.split()[-1] ))

I'll assume that's where the problem lies.
Try checking if the string is not empty before using it:

     for line in f.readlines():
         if line:
            atm_chg.append(float( line.split()[-1] ))


> However, the Variable Explorer shows:

I have no idea what the Variable Explorer is?
Is it part of your IDE? Or of numpy?
If the IDE which IDE are you using?

>   [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
> 
> One line of which is exactly what I want as input to the next step in 
> the larger calculation.
> 
> Now, my question is how do I extract just one line of this file?

Any particular line? And which file are you talking about?
The data should be in the list variable, atm_chg.
In which case the first line is therefore:  atm_chg[0]

Or you can process each line using the usual for loop:

for line in atm_chg:
    # use line here....

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list