List modification doesn't change list

Question:

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.

word = input("Enter a word: ")

word = list(word)
count = 0

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

print(word)

It just returns the original string in list form, even though I’m saving the last letter and inserting it before popping it off of the string? Does word.pop() not capture the last letter of a string before deleting it or am I overlooking something?

Asked By: BVB44

||

Answers:

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']
Answered By: Andrej Kesely

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]
Answered By: Richard Boyne

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!

Answered By: ForceBru

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.

Answered By: Paul M.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.