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
A neat, functional solution, that uses only built-in functions
Output:
I assume that you actually meant something like the comment of Tigerhawk.
Your problem is that
e= (' ') , e
is just overwriting the value ofe
(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 thate
was originally pointing to.You can instead do something like this:
Note the inner loop:
for i in range(len(a)-1,-1,-1):
This is done this way because of 2 reasons:a
since you are going to be changin the values ina
You can use list comprehension and
chain.from_iterable
fromitertools