Home > Net >  Why these scripts don't modify all of the list?
Why these scripts don't modify all of the list?

Time:12-06

I am practicing lists in python. I am trying to change vowel letters in ['a', 'n', 'a', 'c', 'o', 'n', 'd', 'a'] to str 'v'. I used for loop and also range, but anything doesn't occur! What's wrong in my scripts?

Script one:

a = list('anaconda')
vowels = list('aeiou')
for i in a:
    if i in vowels:
        i = 'v'
print(a)

and also tried:

a = list('anaconda')
vowels = list('aeiou')
for i in range(len(a)):
    if i in vowels:
        i = 'v'
print(a)

But both of them returns a without change: ['a', 'n', 'a', 'c', 'o', 'n', 'd', 'a']!

CodePudding user response:

a = list('anaconda')
vowels = list('aeiou')
for i in range(len(a)):
    if a[i] in vowels:
        a[i] = 'v'
print(a)

you are using index as value ,you need to use `a[x] for checking whether character is vowel( present in the given list) or not

CodePudding user response:

Ok, let's change it.

Firstly, understand that "i" in that code

for i in a

is only variable named "i" that equals value from "a" list. When you write

i = 'v' 

you just change variable "i" but not value from "a" list.

Then you need to change not "i" but value from "a".

Write that:

for i in range(len(a)):
   if a[i] in vowels:
      a[i] = 'v'

Solution is using "a[i]" to refer to a value in a list.

  • Related