0

I've been struggling for a while with this. I have a list with sublist and I wanted to add an element that is a space before each element of the sublists. for example:

lin = [[2], [3], [2], [2, 2], [2]]

the result should be:

lin = [[' ',2], [' ',3], [' ',2], [' ',2, ' ',2], [' ',2]]

I've tried to do this:

for a in lin:
    for e in a:
        e = (' ') , e 

but I obtained exactly the same list with no alterations

1
  • Do you mean lin=[[' ',2], [' ',3], [' ',2], [' ',2, ' ',2], [' ',2]]? Commented Dec 4, 2015 at 23:42

3 Answers 3

2

I assume that you actually meant something like the comment of Tigerhawk.

Your problem is that e= (' ') , e is just overwriting the value of e (which was originally each value in your nested list) to a tuple containing a space and the original value. This doesnt actually change anything inside of your list, just changes whatever it is that e was originally pointing to.

You can instead do something like this:

>>> lin = [[2], [3], [2], [2, 2], [2]]
>>> for a in lin:
        for i in range(len(a)-1,-1,-1):
            a.insert(i, ' ')


>>> lin
[[' ', 2], [' ', 3], [' ', 2], [' ', 2, ' ', 2], [' ', 2]]

Note the inner loop: for i in range(len(a)-1,-1,-1): This is done this way because of 2 reasons:

  1. you dont want to be actually looping through a since you are going to be changin the values in a
  2. You need to start with the highest index because if you start from 0, the indexes of the rest of the items ahead of it will change.
Sign up to request clarification or add additional context in comments.

3 Comments

Whoops, didn't notice the [2, 2] element in there. Good work Stomach Whisperer
Uh oh. The name is sticking.
thank you so much for your help and for the explanation! yes I wanted to mean what Tigerhawk said. Thanks again I really appreciate it.
2

You can use list comprehension and chain.from_iterable from itertools

>>> from itertools import chain
>>> lin = [[2], [3], [2], [2, 2], [2]]
>>> [list(chain.from_iterable([(' ', i) for i in j])) for j in lin]
[[' ', 2], [' ', 3], [' ', 2], [' ', 2, ' ', 2], [' ', 2]]
>>> 

Comments

0

A neat, functional solution, that uses only built-in functions

lin = [[2], [3], [2], [2, 2], [2]]

add_spaces = lambda l: [i for x in zip(' '*len(l), l) for i in x]
new_list = [add_spaces(l) for l in lin]

Output:

>>> print new_list
[[' ', 2], [' ', 3], [' ', 2], [' ', 2, ' ', 2], [' ', 2]]

2 Comments

moar functions! lambda l: list(itertools.chain.from_iterable(zip(itertools.repeat(' '), l)))
(and I'm very happy that it worked, since I whipped it together without running it through my repr first...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.