I'm trying to populate a list with a for loop. This is what I have so far:
newlist = []
for x in range(10):
for y in range(10):
newlist.append(y)
and at this point I am stumped. I was hoping the loops would give me a list of 10 lists.
You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.
What is a list of lists? In any programming language, lists are used to store more than one item in a single variable. In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas. It can be used to store integer, float, string and more.
Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.
You were close to it. But you need to append new elements in the inner loop to an empty list, which will be append as element of the outer list. Otherwise you will get (as you can see from your code) a flat list of 100 elements.
newlist = []
for x in range(10):
innerlist = []
for y in range(10):
innerlist.append(y)
newlist.append(innerlist)
print(newlist)
See the comment below by Błotosmętek for a more concise version of it.
You can use this one line code with list comprehension
to achieve the same result:
new_list = [[i for i in range(10)] for j in range(10)]
Alternatively, you only need one loop and append range(10)
.
newlist = []
for x in range(10):
newlist.append(list(range(10)))
Or
newlist = [list(range(10)) for _ in range(10)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With