0

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!

4
Contributors
3
Replies
40
Views
2 Years
Discussion Span
Last Post by snippsat
Featured 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] Read More

  • 2

    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', … Read More

  • 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 … Read More

2

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

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

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]
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.