Jeremy
Jeremy

Reputation: 876

for loops in Python: list assignment index out of range

I am very new to Python. I have to write a for loop. For example, there are 2 files, say "files". I need to extract the data from each. My codes are below, however, it keeps giving me the error:

list assignment index out of range.

I've searched for existing answers, but sorry I don't understand how to apply to my case. Many Thanks.

import xarray as xr
ds = []
for i in range(0,2):
       ds[i] = xr.open_dataset(files[i])

Upvotes: 0

Views: 220

Answers (3)

Emmanuel Ban
Emmanuel Ban

Reputation: 105

You don't have to use lists indexed, like in C. Just use append(). Also, you need to declare the files list too, where you store the files. And you can call the range method with the length of files list.

Method 1, with index and classic for loop:

import xarray as xr
ds = []
for i in range(len(files)):
       ds.append(xr.open_dataset(files[i]))

Method 2, without index and for each loop:

import xarray as xr
ds = []
for file in files:
       ds.append(xr.open_dataset(file))

Method 3, with list comprehension:

import xarray as xr

ds = [xr.open_dataset(file) for file in files]

Upvotes: -1

theashwanisingla
theashwanisingla

Reputation: 477

You’ve two ways to achieve this viz append and insert. append is used to add the content at the end of the list while insert can insert the element at any location of the list. As of now, you’re trying to add some element to the Blank list, so append is a good option. Best answer for your question is:


for file in files: 
    ds.append(xr.open_dataset(file))

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

Just do:

ds = []
for file in files: 
    ds.append(xr.open_dataset(file))

You don't need to use indices at all.

Even shorter and cleaner, as you are building a list, you can use a list comprehension:

ds = [xr.open_dataset(file) for file in files]

Upvotes: 1

Related Questions