Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modifying Element with Index in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading