Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List clarification: Assigning values directly is not possible

Given value = [], what is the difference between the following code snippets?

snippet 1:

for i in range(t):
    value[i] = 'yes'

snippet 2:

value += input.split()

In the first case, I am getting an error "IndexError: list assignment index out of range"

The second case seems to be working correctly without any error.

like image 704
Sree Avatar asked Jan 27 '23 01:01

Sree


2 Answers

In the first example, you are trying to insert 'yes' into the list at an index it does not have. (Because an empty list has no position to insert anything into.)

In the second example, you are extending the list with the elements of the iterable input.split()1, because

my_list += iterable

is equivalent to

my_list.extend(iterable)

Demo:

>>> my_list = []
>>> my_list.extend('Hi Sree'.split())
>>> my_list
['Hi', 'Sree']
>>> 
>>> my_list = []
>>> my_list += 'Hi Sree'.split()
>>> my_list
['Hi', 'Sree']

1input already is the name of a builtin function. Use another name in order to not shadow the bultin.

like image 153
timgeb Avatar answered May 15 '23 17:05

timgeb


Your first example tries to access the ith element of the list and set it to a value. Since your list is an empty list this element does not exist and therefore you get an error.

To get this first snippet working, you would have to append values:

values = []
for i in range(t):
    values.append(i)

The second example uses the fact that when adding two lists with + you create a new list with all elements of the second being at the end. By using += this new list is assigned to values again.

The second snippet could also use extend:

values.extend(input.split())
like image 23
Graipher Avatar answered May 15 '23 19:05

Graipher