Reputation: 13
I am trying to write a function in python that should take as input 2 arguments as follow f('k', range(4)) and should return the following:
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
I have tried the following but something goes wrong
def f(j,ls):
return [[ls.insert(x,j)]for x in ls]
Does anyone know how to find the solution?
Upvotes: 1
Views: 164
Reputation: 11134
This should work for you.
def f(j,num):
lst=[]
for i in range(num+1):
innerList=list(range(num))
innerList[i:i]=j
lst.append(innerList)
return lst
Demo:
print f("j",4)
Output:
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
Upvotes: 0
Reputation: 1121952
list.insert()
returns None
because the list is altered in-place. You also don't want to share the same list object, you'll have to create copies of the list:
def f(j, ls):
output = [ls[:] for _ in xrange(len(ls) + 1)]
for i, sublist in enumerate(output):
output[i].insert(i, j)
return output
You also could use slicing to produce new sublists with the extra element 'inserted' through concatenation; this then gives you one-liner list comprehension:
def f(j, ls):
return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]
Demo:
>>> def f(j, ls):
... output = [ls[:] for _ in xrange(len(ls) + 1)]
... for i, sublist in enumerate(output):
... output[i].insert(i, j)
... return output
...
>>> f('k', range(4))
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
>>> def f(j, ls):
... return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]
...
>>> f('k', range(4))
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
Upvotes: 2