D
D
dintear_koden2021-07-21 19:14:19
Python
dintear_koden, 2021-07-21 19:14:19

Changing the third element in the list does not work?

I made a solution for such a problem:
The user enters integers and you need to create a dictionary whose keys will be only even numbers, and the values ​​will be the squares of these numbers.

And did this:

# digits = input("Вводите целые числа через пробел: ")
digits = "2 4 5 8 6"
digits_list = digits.split(" ")

for i in range(len(digits_list) - 1):
  if int(digits_list[i]) % 2 == 0:
    digits_list[i] = [int(digits_list[i]), int(digits_list[i]) ** 2]
    continue
  else:
    del digits_list[i]

print(digits_list)

But it is the third element in the list that does not change like all the others. Tried to find what was wrong, but couldn't. Tell me who knows.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Krostelev, 2021-07-21
@dintear_koden

remove the else block.
You remove an element from the list, which causes the indexes to shift.
If you add another odd number to the source data, there will be an error in general, because the code is incorrect.
And a dictionary is not a list within a list.
Read what a dictionary is, create a separate variable for it.
This task is solved literally in one line, except for the input statement

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question