Python beginner. List insert related questions. IndexError: list assignment index out of range

Asked 2 years ago, Updated 2 years ago, 41 views

a=[1,2,3,4,5]

Print a list b tripling each element of the list called #a
#Sol(Use for sentence)

'''
b=[]
i=0
for v in a:
        b.insert(i,3*v)
        i=i+1
print(b)
'''

b=[]
i=0
for v in a:
        b[i]=3*v
        i=i+1
print(b)

At first, I tried to print out b as the code below

Traceback (most recent call last):
  File "C:/Users/whdud/PycharmProjects/tw100/basic/__init__.py", line 19, in <module>
    b[i]=3*v  

IndexError: list assignment index out of range

I got an error and it didn't work.

I was trying to figure out which element I got the error, and I remembered the element insert function on the list, so I changed it to '' and ran it well, but why does the error appear if I add the element to the blank list b?

I think it'

'Because the list b was initially defined as blank, there was an error because it was impossible to change the value of the element because each element was missing (undefined). I think so. Is that the right reason? So the insert function is a function that can add elements to the place with or without elements?

It's my first time to start coding, but I was learning by myself with a book, and I'm asking this question because I have a question

python

2022-09-20 15:44

1 Answers

Can I ask you a question?

Yes.

In my opinion, because we defined the list b as a space in the first place, there was an error because each element was missing (undefined) and it was impossible to change the value of the element. I think so. Is that the right reason?

Yes. It's a problem that can't be changed to something (b*v) because there's no b[0] exactly.

So the insert function is a function that can add elements to the place with or without elements?

I'm not sure about that, but list.Let's examine the insert() method itself.

Inserts the item in the given location. The first factor is the index that the inserted element will have. So a.insert(0,x) is inserted at the beginning of the list, and a.insert(len(a),x) is equivalent to a.append(x).

If you look at what you're going to have, it seems that you can handle it with or without elements.


2022-09-20 15:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.