Reputation: 59
I have a loop to populate a list, using a loop format.
I'm supposed to create a list, then - using a loop - populate the list with N elements, and set each list element to its index multiplied by 10.
It is also possible that N will be 0. In this case I'm supposed to output an empty list [], and this what I think is tripping me up.
list = [N]
for x in range(N):
innerlist = []
for y in range(N):
innerlist.append(list)
list.append(innerlist)
if N == 0:
list = []
print (list)
I thought that the if(N==0)
statement would reset the value of the list but it doesn't. I should output []
but instead I output [0]
.
Upvotes: 3
Views: 22447
Reputation: 69
>>> N = 10
>>> my_list = [iter * 10 for iter in range(N)]
>>> print(my_list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> N = 0
>>> my_list = [iter * 10 for iter in range(N)]
>>> print(my_list)
[]
Upvotes: 7
Reputation: 1
myList = []
if N == 0:
print(myList)
else:
for i in range(N):
myList.append(i * 10)
print(myList)
Upvotes: 0
Reputation: 1
I'm just a beginner myself, but I found this online that matches your question. I have no idea how to format the actual code right, but hopefully this helps!
my_list = []
my_newlist =[]
if N <= 0:
print(my_list)
else:
for x in range(N):
my_list.append(x)
my_newlist= [i* 10 for i in my_list] # not getting the statement 'i * 10 for in i' statement
print(my_newlist)
[Python] #We provide you with a number N. #Create a list then, using a loop, populate - Pastebin.com. (2017, November 29). Retrieved from https://pastebin.com/2F0zXq6z
Upvotes: -1
Reputation: 5148
If you just add the condition before entering the whole loop, you'll get the expected result:
N = 10
list = []
if (N > 0):
for i in range(N):
list.append(i*10)
print(list)
# output: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Upvotes: 0
Reputation: 1256
lst = range(8)
innerlst = []
for i in lst:
if 0 in lst:
innerlst = []
continue
else:
innerlst.append(i*10)
Upvotes: 1