Why Does This Iterative List-Growing Code Give Indexerror: List Assignment Index Out of Range

Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list?

j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.

Try the following instead, to add a new element to the end of the list:

for l in i:
j.append(l)

Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:

j = list(i)

Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:

i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0

for l in i:
j[k] = l
k += 1

The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.

Why is my for-loop index giving IndexError: list assignment index out of range?

This line should fix it:

z = [0] * len(element)

and later:

for k in range(1, len(element)):

as Ronald points out.

Problem with list assignment index out of range Python

The problem is the empty tuple in your list lT, which does not have a last element, therefore you cannot access it with lst[-1].

Instead of changing lists, create new ones:

def replace_last(tuples, object):
return [
tup[:-1] + (object, )
for tup in tuples
]

IndexError: list index out of range in very simple 3 lines of Python code

It's not clear what exactly you're trying to do. When you iterate over an iterable like a list with

for i in my_list:

each i is each member of the list, not the index of the member of the list. So, in your case, if you want to print each member of the list, use

for i in my_list:
print(i)

Think about it: what if the 3rd member of the list was 9, for example? Your code would be trying to print my_list[9], which doesn't exist.

IndexError: list assignment index out of range for CNN program from scratch

The error is in

def sum(inputs):
sum_row=[]
for i in range(len(x_train)):
for a in range(32):
for b in range(32):
sum_row[i]=0
sum_row[i]+= inputs[i][a][b][1]
return sum_row

The reason for the error is that you are trying to access an element of sum_row, but sum_row doesn't have any element in it (as you set it to [] before the for loops). Inside the for loops, you try to access members which it doesn't have. Instead of doing sum_row[i] = 0 you should be doing sum_row.append(0) which adds an element to that list. Then you can access it via sum_row[-1] += inputs[i][a][b][1]

IndexError: list assignment index out of range in Python

your list is empty. perl will expand array automatically but python won't.

C.append(int(raw_input()))

instead.

While-loop - IndexError: list assignment index out of range

I think the only change you need to make is from:

indexes[x] = decoded.find(special_string, total)
to:

indexes.append(decoded.find(special_string, total))

You can't assign indexes[x] since it doesn't exist.

IndexError: list assignment index out of range [python + json]

It's probably easier to work this out via an answer.

This works for a JSON file where your values are numeric. In your version they're strings but that would make the solution a little more difficult to work with since you'd have to convert strings to numbers in order to do math on them.

For example, this is what the JSON should look like, and what Python's json module will try to write by default since you basically have a mapping of str: int for your dict keys.

{
"| name ": 1716,
"| name_1 ": 4291,
"| name_2 ": 4778,
"| name_3 ": 1254
}

Now, here's a version of your code that probably does what you want based on what we discussed in the comments.

Notice that there are some changes to how everything is loaded and modified.

if "!sell" in message.content:
k = f"| {message.author.name} "
val = random.randrange(1000, 5000)

# open entire file for reading and writing
with open("income.json", "r+") as f:
incomes = json.load(f)

# Either add the value to the user's balance
# or, if they don't exist yet, create the entry
# with the val
try:
incomes[k] += val
except KeyError:
incomes[k] = val

# seek to beginning and rewrite file
f.seek(0)
json.dump(incomes, f, indent=4)
f.truncate()

await message.channel.send(f"You Earned {val} Dollars from selling")


If you need to convert your JSON file...

import json

with open("income.json", "r+") as f:
d = json.load(f)
n = {k: int(v) for k, v in d.items()}
f.seek(0)
json.dump(n, f, indent=4)
f.truncate()


Related Topics



Leave a reply



Submit