0

I'm struggling with list comprehensions. I need to write a function that will add 0 for every N numbers. The function looks like this:

def makeSpace(list, space):
    list = [list.insert(i, 0) for i in list if ....]
    return list

Example, Im passing makeSpace(list,2) and if my list looked like: 1,2,3,4,5,6 then after the function should return 1,2,0,3,4,0,5,6,0

Can someone tell me how to make it?

PS: If for loop is better for it, it can be traditional for loop I found in a duplicate question something and change in on my own:

def fun(lst, space):
    i = space
    while i < len(lst):
        lst.insert(i, 0)
        i += space+ 1
    return lst

But it does not add number at the end, for example for every 3 space: [1, 2, 3, 0, 4, 5, 6] it should add also after 6 What should I change?

must
  • 27
  • 7

2 Answers2

3

You can do something horrendous, like this:

>>> n = 2
>>> lst = 1,2,3,4,5,6
>>> [x for i in range(0, len(lst), n) for sub in (lst[i:i+n],(0,)) for x in sub]
[1, 2, 0, 3, 4, 0, 5, 6, 0]

This is hard to read, and less efficient than a naive implementation using a simple for-loop. Don't use this.

It is much better to write clean, well-organized code rather than trying for no reason to write a list-comprehension. If the list-comprehension version doesn't seem obvious, then it almost certainly isn't worth writing. Consider the following solution:

>>> def chunk_list_by_n(lst, n):
...     for i in range(0, len(lst), n):
...         yield lst[i:i+n]
...
>>> def foo(lst, n):
...     result = []
...     for chunk in chunk_list_by_n(lst, n):
...         result.extend(chunk)
...         if len(chunk) == n:
...             result.append(0)
...     return result
...
>>> foo((1,2,3,4,5,6),2)
[1, 2, 0, 3, 4, 0, 5, 6, 0]

I've used more lines, but I've split up my program into reusable components. When I come back and re-read this a month from now, it will be easier to understand than that horrendous one-liner.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
3

Here's a version with a simple for loop and an independent counter that you increment:

test = [1, 2, 3, 4, 5, 6]
idx = 1
new = []
for num in test: 
    new.append(num)
    if idx % 3 == 0:
        new.append(0)

    idx += 1 

print(new)
[1, 2, 3, 0, 4, 5, 6, 0]
scratchpad
  • 276
  • 1
  • 6