Reputation: 577
I have a list:
list1=[[2,3],[4,5],[6,7]]
I want to add a single value "one" to all sublist in the list at index 2
final output should be:
list2=[[2,3,"one"],[4,5,"one"],[6,7,"one"]]
tried with:
for list2 in list1:
print list2.insert(2,"one")
But its showing error as None
.
Upvotes: 1
Views: 946
Reputation: 1
List_1 = [[2,3],[4,5],[6,7]]
List_2 = [ ]
For i in List_1: #Selecting a sub-list at each iteration
temp = i.append('one') #Adding 'one' to the sub-list
List_2.append() #Adding the modified sublist to List_2
Result:
Print(List_2)
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
Upvotes: 0
Reputation: 106891
The list.insert()
function modifies the list without returning it.
You should print the list afterwards:
for list2 in list1:
list2.insert(2,"one")
print(list1)
Alternatively, what you want to do can be more easily achieved with list comprehension:
list1=[[2,3],[4,5],[6,7]]
list2=[i + ["one"] for i in list1]
print(list2)
Both pf the above output:
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
Upvotes: 2
Reputation: 13426
You need:
list1=[[2,3],[4,5],[6,7]]
for l in list1:
l.append("one")
Output:
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
Upvotes: 3
Reputation: 3070
Change your code as below :
list1=[[2,3],[4,5],[6,7]]
for subList in list1:
subList.append("one")
print list1
Output is :
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
Upvotes: 3
Reputation: 12015
Just use list comprehension
>>> list1 = [[2,3],[4,5],[6,7]]
>>> [e + ['one'] for e in list1]
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
Upvotes: 2
Reputation: 164773
list.insert
is an in-place operation and returns None
. Instead, you can use a list comprehension:
L = [[2,3],[4,5],[6,7]]
res = [[i, j, 'one'] for i, j in L]
print(res)
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
Upvotes: 4
Reputation: 5709
It's because list.insert
in python does not return any value. So your code inserts value to list correctly but you try to print this list wrong way. It should be:
for list2 in list1:
list2.insert(2,"one")
print list2
Upvotes: 1