Ted Idzikowski Ted Idzikowski - 1 month ago 11
Python Question

Using .strip() to remove spaces in every element of a 2D list

I would like to know how you can use .strip() function in a 2D list so that in each element of each list inside a list, you can remove the useless spaces inside the strings.

Here's my attempt in the shell:

>>> questions = [['1986 ',' Baby', 'Shaw ', ' Welcome'],['1976',' fJKC','cbv bv ',' byt']]
>>> [['1986 ',' Baby', 'Shaw ', ' Welcome'],['1976',' fJKC','cbv bv ',' byt']]

>>> for z in range(len(questions)):
for t in range(len(questions[z])):
>>> questions
>>> [['1986 ', ' Baby', 'Shaw ', ' Welcome', '1986', 'Baby', 'Shaw', 'Welcome'], ['1976', ' fJKC', 'cbv bv ', ' byt', '1976', 'fJKC', 'cbv bv', 'byt']]

However, this is not the way I want it to return. My expected outcome is that after writing the code, questions equals to this:

>>> questions
>>> [['1986', 'Baby', 'Shaw', 'Welcome'], ['1976', 'fJKC', 'cbv bv', 'byt']]

Please, do not use numpy or any functions that need to be imported. Also, please make the solution general, so it can be applied to a 2D list with not only 2 elements (as in my case) but many elements (for everyone).

  1. You don't need to use index to iterate the list. Just iterate.
  2. list.append does not change item in place; use list[i] = ... to change item. or list[:] = ... to changed all items.

Here's the one that use simple iteration and list slice assignment (list[:] = ...) to replace items in-place with list comprehension:

questions = [['1986 ',' Baby', 'Shaw ', ' Welcome'], ['1976',' fJKC','cbv bv ',' byt']]

for q in questions:
    q[:] = [info.strip() for info in q]

    # Alternatives
    # q[:] = (info.strip() for info in q)  # generator expression
    # q[:] = map(str.strip, q)  # `map` with unbound method `str.strip`

# question => [['1986', 'Baby', 'Shaw', 'Welcome'], ['1976', 'fJKC', 'cbv bv', 'byt']]