Hi I dont want the extra bracket inside the list thats been outputted so how would I fix that?
This is the code:

def my_code(list1, list2, index):
    index = ['a','b','c']
    list2 = [2]
    list1 = [1,2,3]
    list1.insert(2,index)
    return list1

and it returns:

[1, 2, ['a', 'b', 'c'], 3]

I dont want the brackets from inside!

Recommended Answers

All 3 Replies

Use slice and extend(), for example:

mylist1 = [1,2,3]
mylist2 = ['a','b','c']

# slice mylist into two temporary lists at index 2
t1 = mylist1[0:2]
t2 = mylist1[2:]

# now use list extend()
t1.extend(mylist2)
t1.extend(t2)

print(t1)  # [1, 2, 'a', 'b', 'c', 3]

Another option, insert one element at a time. Do it in reverse order if you want to keep the insert position constant ...

mylist1 = [1,2,3]
mylist2 = ['a','b','c']

for e in reversed(mylist2):
    # insert each element e at index 2 of mylist1
    mylist1.insert(2, e)

print(mylist1)  # [1, 2, 'a', 'b', 'c', 3]

With enumerate().

>>> mylist1 = [1,2,3]
>>> mylist2 = ['a','b','c']
>>> for index, item in enumerate(mylist2, 2):
...     mylist1.insert(index, item)
...     
>>> mylist1
[1, 2, 'a', 'b', 'c', 3]

Flatten list approach.

def flatten(container):
    for i in container:
        if isinstance(i, list):
            for j in flatten(i):
                yield j
        else:
            yield i

def my_code(list1, list2, index, flatten):
    list1.insert(2,index)
    return list(flatten(list1))

if __name__ == '__main__':
    list1 = [1, 2, 3]
    list2 = [2]
    index = ['a','b','c']
    print my_code(list1, list2, index, flatten)
    #--> [1, 2, 'a', 'b', 'c', 3]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.