1

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?

2
  • @ImanK: It'll produce a list of [None] sublists. Commented Oct 25, 2015 at 22:07
  • Read the documentation for list.insert, see what it returns. Commented Oct 25, 2015 at 22:07

2 Answers 2

2

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']]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.