0

I have an array called mylist, which has 3 elements. And I want to strip() every element in that array. Here is code

mylist = ['  A  ', '  B   ', '    C']

for x in len(mylist):
    mylist[x] = mylist[x].strip()

print(mylist)

This code gave an error

TypeError: 'int' object is not iterable
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • in python mostly we create new array with new values and at the end we assing it to the same variable. Using list comprehension it would be `mylist = [x.strip() for x in mylist]` or using `map` it could be `mylist = list(map(str.strip, mylist))` – furas Dec 21 '19 at 07:45
  • pd.DataFrame(mylist)[0].str.strip().tolist() #: ['A', 'B', 'C'] – oppressionslayer Dec 21 '19 at 07:49

4 Answers4

5

The issue is that len(mylist) returns a single number. You're missing a range function. Personally, I would suggest using enumerate instead.

For example, If you want the same list

for i, x in enumerate(mylist):
    mylist[i] = x.strip()

If you want a new list

lst = [x.strip() for x in mylist]
# or
lst = list(map(str.split, mylist)) 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
3

Method-1: List Comprehenion

You could do this simply by using a list comprehension as follows (which is more pythonic).

[x.strip() for x in mylist]

Output:

['A','B','C']

Method-2: Enumerate

Also, if you must use an index while iterating over a list, I would strongly suggest you to use enumerate(mylist) as follows.

for i, x in enumerate(mylist):
    mylist[i] = x.strip()
print(mylist)

Output:

['A','B','C']

Reference

  1. Is there a need for range(len(a))?
CypherX
  • 7,019
  • 3
  • 25
  • 37
2

Change len(mylist) to range(len(mylist))

mylist = ['  A  ', '  B   ', '    C']

for x in range(len(mylist)):
    mylist[x] = mylist[x].strip()

print(mylist)

By the way, I would use list comprehension in this case:

mylist = ['  A  ', '  B   ', '    C']
newlist = [x.strip() for x in mylist]
9mat
  • 1,194
  • 9
  • 13
1

Your code for x in len(mylist) will convert into for x in 3 which isn't valid. Hence, the error TypeError: 'int' object is not iterable.

Update:

for i, x in enumerate(mylist):
    mylist[i] = x.strip()

stud3nt
  • 2,056
  • 1
  • 12
  • 21
  • So, what's the solution? – OneCricketeer Dec 21 '19 at 07:49
  • Solution would be to either enumerate over the list or use `range` function and update according to the requirement. I know I should have included that but was hoping the OP will understand the problem and figure it out. But thanks, have included it in my answer. – stud3nt Dec 21 '19 at 07:52