Advertisements
I am a beginner in Python. I am learning currently how to Modify an element with index
MyCode:
data = [4, 6, 8]
for index, value in enumerate(data):
data[index] = data[index] + 1
value = value * 2
print(data)
print(value)
Terminal Output:
[5, 7, 9]
16
Terminal Output Expectation:
[5, 7, 9]
[8, 12, 16]
Why didn’t I get my expected output? Now I have tried to define an empty_list before my FOR loop and then add the VALUE variable to it, then print(the_empty_list)
Here:
data = [4, 6, 8]
empty_list = []
for index, value in enumerate(data):
data[index] = data[index] + 1
value = value * 2
**(How to add VALUE to the empty_list)**
print(data)
print(empty_list)
** **I am finding the asterisked part difficult. Who knows what I should do here?
>Solution :
If your list is empty you can’t access it with an index. Use append
method to add new elements:
data = [4, 6, 8]
empty_list = []
for index, value in enumerate(data):
data[index] = data[index] + 1
value = value * 2
empty_list.append(value)
print(data)
print(empty_list)
Output:
[5, 7, 9]
[8, 12, 16]