I
I
IntoTheSurf2020-09-15 10:59:53
Python
IntoTheSurf, 2020-09-15 10:59:53

Why are the values ​​from the loop not saved?

Hello)

S1 = 'Зайцы и пчелы прыгают по лужку'
lenght = 5
res = S1.split()

for i in res:
    if len(i) == lenght:
        i = i[:-3]
        print (i)

print(res)

But there is a question - why is the new value i that we changed in the loop not stored in res?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
giroskop grospop, 2020-09-15
@IntoTheSurf

Hi, the i variable does not refer to res. Each iteration of the loop i is assigned the value of an element from res.
In order to overwrite values ​​in res, you need to access res directly.
For example something like this

S1 = 'Зайцы и пчелы прыгают по лужку'
lenght = 5
res = S1.split()

for i in range(len(res) - 1):
    if len(res[i]) == lenght:
        res[i] = res[i][:-3]
        print (res[i])

print(res)

P
PavelMos, 2020-09-15
@PavelMos

Because this is not a loop through the list index with a step (for i in range .....), but a loop through the list elements themselves, where the next element is written to i

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question