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.
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.
Your first example tries to access the i
th 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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With