Stef1611
Stef1611

Reputation: 2387

python : problem with insertion in a list

I have written the following code that works and the output is what it is expected :

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i in range(3):
    temp=myList1[i]
    temp.insert(0,myList2[i])
    myList3.append(temp)
print(myList3)

But when I try to write the same code without the temp variable, it does not work.

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i in range(3):
    myList3.append(myList1[i].insert(0,myList2[i]))
print(myList3)

And this code, also, does not work.

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i in range(3):
    temp=myList1[i].insert(0,myList2[i])
    myList3.append(temp)
print(myList3)

I think there are some python fundamentals that I have not understood.

Any comments and help will be appreciated.

Thanks for answer

Upvotes: 1

Views: 78

Answers (3)

clemens
clemens

Reputation: 115

Take a look at your last example: The line: temp=myList1[i].insert(0,myList2[i]) does change your list "myList1"! The problem is, that the result of the insert will return "None".

So something like this would work, but not be pretty:

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i in range(3):
    myList1[i].insert(0,myList2[i])
    myList3.append(myList1[i])
print(myList3)

Upvotes: 1

sighingnow
sighingnow

Reputation: 821

.insert of list returns None, rather than the result list.

To avoid the usage of temporary variable tmp, you could have

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i in range(3):
    myList3.append(myList2[i:i+1] + myList1[i])
print(myList3)

Or

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i in range(3):
    myList3.append([myList2[i]] + myList1[i])
print(myList3)

Upvotes: 1

user15801675
user15801675

Reputation:

.insert is an inplace function. It returns None or nothing. If you don't want to use temp, you can use zip()

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]
myList3=[]
for i,j in zip(myList1,myList2):
    i.insert(0,j)
    myList3.append(i)
print(myList3)

A compact solution:

myList1=[[1,2],[3,4],[5,6]]
myList2=["abc","def","ghi"]

myList3=[[j]+i for i,j in zip(myList1,myList2)]
print(myList3)

Upvotes: 2

Related Questions