Reputation: 197
def make_list_of_lists(n):
the_list = []
sublist = []
for i in range(n):
print(sublist)
the_list.extend(sublist)
sublist = sublist.insert(len(sublist), i+1)
return the_list
I got a error message of this function, which is:
'NoneType' object is not iterable'
I don't understand why this happen?
Upvotes: 0
Views: 115
Reputation: 4391
As noted in other answers, it is the sublist = sublist.insert(len(sublist), i+1)
line that causes the problem.
However, you seem to be wanting to make a list of lists (based on the function name), which your code currently does not do.
def make_list_of_lists(n):
the_list = []
sublist = []
for i in range(n):
the_list.append(sublist)
return the_list
print(make_list_of_lists(5))
This prints an empty list of 5 empty lists:
[[], [], [], [], []]
Upvotes: 0
Reputation:
sublist = sublist.insert(len(sublist), i+1)
This makes sublist to be none. That is the problem.
Upvotes: 0
Reputation: 54148
The insert
operation modifying the object inplace, and like a almost all of these kind of method it returns None
because you don't need the return value. After 1 iteration it tried to do the following which requires to iterate over None
to add all of its elements, and you can't
the_list.extend(None)
So just do
sublist.insert(len(sublist), i + 1)
Upvotes: 1
Reputation: 4377
Look at this line:
sublist = sublist.insert(len(sublist), i+1)
insert
function does insert in place and returns None
, so on next iteration here
the_list.extend(sublist)
sublist
is None
while extend
function requires iterable parameter. Fixed code:
def make_list_of_lists(n):
the_list = []
sublist = []
for i in range(n):
print(sublist)
the_list.extend(sublist)
sublist.insert(len(sublist), i + 1)
return the_list
make_list_of_lists(3)
[]
[1]
[1, 2]
[1, 1, 2]
Upvotes: 4