简体   繁体   中英

List modification doesn't change list

I'm trying to reverse a string, so I converted the string into a list and was trying to send the last element to the front, 2nd to last element to the 2nd space, etc.

def backwards():
    word = input("Enter a word: ")
    word = list(word)
    steps = 0
    while steps < (len(word)):
        index = -1
        count = 0
        word.insert(count, word[index])
        word.remove(word[index])
        count = count + 1
        steps = steps + 1
    print(word)

It just returns the original string in list form, I'm not sure why it does this?

Here's an experiment:

>>> word = list('python')
>>> word.insert(0, word[-1])
>>> word
['n', 'p', 'y', 't', 'h', 'o', 'n']
>>> word.remove(word[-1])
>>> word
['p', 'y', 't', 'h', 'o', 'n']

Wait, what?!

>>> help(word.remove)
Help on built-in function remove:

remove(value, /) method of builtins.list instance
    Remove first occurrence of value.

    Raises ValueError if the value is not present.

Remove first occurrence of value.

So, you inserted word[-1] at the beginning of the list, and then word.remove immediately removes the first occurrence of word[-1] , which is now at the beginning of the list, you've just inserted it there!

You're setting the variables inside the while-loop to the same value. Also, use list.pop to remove the element from the list. For example:

word = input("Enter a word: ")

word = list(word)
count = 0

while count < len(word):
    word.insert(count, word.pop())
    count = count + 1

print(word)

Prints:

Enter a word: book
['k', 'o', 'o', 'b']

Well the simplest way to do what you are trying is to slice the string in reverse order, this does not even require changing into a list:

word = input("Enter a word: ")
return word[::-1]

Here is the docstring for list.remove :

>>> help(list.remove)
Help on method_descriptor:

remove(self, value, /)
    Remove first occurrence of value.
    
    Raises ValueError if the value is not present.

>>> 

As you can see, list.remove removes the first occurrence of the given value from the list. All your backwards function does right now is take the last character of the word, add it to the front and then immediately remove it from the front again. You do this once for every character in the word, the net result being no change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM