256

I tried writing some code like:

i = [1, 2, 3, 5, 8, 13]
j = []
k = 0

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

But I get an error message that says IndexError: list assignment index out of range, referring to the j[k] = l line of code. Why does this occur? How can I fix it?

2
  • 10
    append is the right solution for your use case, however there's an insert method on python list which can insert directly to the i'th position in list. j.insert(k, l) Commented Sep 30, 2015 at 8:46
  • May I ask, why would not OP's solution work? Why use append?
    – Helen
    Commented Jun 10, 2018 at 16:01

10 Answers 10

402

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.

6
  • 2
    OK, thank you very much. I didn't know which one to praise as there are three almost same answers. This is most descriptive I think. Cheers
    – Vladan
    Commented Apr 13, 2011 at 18:11
  • 2
    I can see that this can be very confusing for those coming from other languages like PHP or C. j is a type of list, not an array. With list type, I don't think this is subscriptable. Very confusing if coming from other languages.
    – Nguai al
    Commented Jan 12, 2019 at 23:24
  • @Nguaial The list type is subscriptable, but you can only access elements that already exist - you can't create an element by attempting to write to an index that is out of range. j[0] = "foo" will work if the list already has at least one element. Commented Jan 28, 2019 at 13:49
  • I wonder about reasons behind this design decision...
    – x-yuri
    Commented Dec 6, 2020 at 20:15
  • after using the append it show the error cannot assign to function call Commented Jul 20, 2021 at 11:25
67

Your other option is to initialize j:

j = [None] * len(i)
0
30

Do j.append(l) instead of j[k] = l and avoid k at all.

3
  • 3
    A shorter (more Pythonic?) way might be j+=[l] Commented Apr 13, 2011 at 18:05
  • 2
    @BlaXpirit: It will put burden to the garbage collector, I think.
    – khachik
    Commented Apr 13, 2011 at 18:06
  • 4
    @BalXpirit: Given that is only saves a few characters (especially since you need to add spaces for it to be acceptable) and that .append is by far more common (perhaps for a reason - I think it's slightly easier to comprehend), not really superior in any way. (Edit @khachik: No, += modifies in-place)
    – user395760
    Commented Apr 13, 2011 at 18:08
19

You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]
2
  • that second construction is neat Commented Feb 17, 2018 at 12:10
  • 3
    If the only goal is to copy the list, you can simply say j = list(i) I think the question is more about the behaviour of lists, rather than specifically needing a way to copy elements. Commented Jan 16, 2019 at 11:48
11
j.append(l)

Also avoid using lower-case "L's" because it is easy for them to be confused with 1's

2
  • In a monospace font, l is quite different than 1 Commented Apr 4, 2021 at 15:25
  • To me it's not.
    – Tom
    Commented Apr 4, 2021 at 16:10
8

I think the Python method insert is what you're looking for:

Inserts element x at position i. list.insert(i,x)

array = [1,2,3,4,5]
# array.insert(index, element)
array.insert(1,20)

print(array)

# prints [1,20,2,3,4,5]
4
  • 1
    There is no point using insert when append was provided specifically for this purpose.
    – holdenweb
    Commented Oct 26, 2019 at 12:34
  • 1
    On a point of information, your code in fact prints [1, 20, 2, 3, 4, 5].
    – holdenweb
    Commented Oct 26, 2019 at 12:35
  • You inserted at index 1, displacing indices 1 and onwards. The inserted value does not end up at index 2. Iist.insert() is only really needed when you don’t want to add the item at the end of the list; the question here does exactly that so list.append() is preferable. Commented Oct 26, 2019 at 13:34
  • Actually why I answer this question like that I am also suprised :D Do not know what I thought :) This is exactly "list.append()" which is the accepted answer. I think it helps people or give an idea to solve their problems so it gets 5 hits. Commented Oct 28, 2019 at 8:33
7

You could use a dictionary (similar to an associative array) for j

i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0

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

print(j)

will print :

{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}
1
  • For consecutive indicies starting at 0 a mapping is usually the wrong data structure, especially when mappings do not have slicing or reversing as they are not intended to convey any specific order. Commented Oct 26, 2019 at 13:37
2

One more way:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

In this case j will be a numpy array

1

Maybe you need extend()

i=[1,3,5,7]
j=[]
j.extend(i)
0
0

Clearly, the append method should be used for readibility. Likely not recommended, I want to point out that appending also works with slicing or list concatation. Replacing j[k] = l, by one of the following possibilities, would fix your problem, too:

j[k:] = [l]
j[k:] = l,
j += l,

I also like to mention that appending with j[k] = l can work in other languages, like e.g. javascript.

Not the answer you're looking for? Browse other questions tagged or ask your own question.