Ted Idzikowski Ted Idzikowski - 15 days ago 5
Python Question

Using .strip() for 2D list

First question

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[z].append(questions[z][t].strip())
>>> 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']]

Answer
  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']]
Comments