phoenixdown
phoenixdown

Reputation: 838

How to iterate through a list and update values with .strip()

If I have a list of strings and want to eliminate leading and trailing whitespaces from it, how can I use .strip() effectively to accomplish this?

Here is my code (python 2.7):

for item in myList:
    item = item.strip()
    print item

for item in myList:
    print item

The changes don't preserve from one iteration to the next. I tried using map as suggested here (https://stackoverflow.com/a/7984192) but it did not work for me. Please help.

Note, this question is useful:

  1. An answer does not exist already
  2. It covers a mistake someone new to programming / python might make
  3. Its title covers search cases both general (how to update values in a list) and specific (how to do this with .strip()).
  4. It addresses previous work, in particular the map solution, which would not work for me.

Upvotes: 0

Views: 3721

Answers (2)

phoenixdown
phoenixdown

Reputation: 838

I'm answering my own question here in the hopes that it saves someone from the couple hours of searching and experimentation it took me.

As it turns out the solution is fairly simple:

index = 0
for item in myList:
    myList[index] = item.strip()
    index += 1

for item in myList:
    print "'"+item+"'"

Single quotes are concatenated at the beginning/end of each list item to aid detection of trailing/leading whitespace in the terminal. As you can see, the strings will now be properly stripped.

To update the values in the list we need to actually access the element in the list via its index and commit that change. I suspect the reason is because we are passing by value (passing a copy of the value into item) instead of passing by reference (directly accessing the underlying list[item]) when we declare the variable "item," whose scope is local to the for loop.

Upvotes: 2

Kevin
Kevin

Reputation: 76244

I'm guessing you tried:

map(str.strip, myList)

That creates a new list and returns it, leaving the original list unchanged. If you want to interact with the new list, you need to assign it to something. You could overwrite the old value if you want.

myList = map(str.strip, myList)

You could also use a list comprehension:

myList = [item.strip() for item in myList]

Which many consider a more "pythonic" style, compared to map.

Upvotes: 3

Related Questions