aList = []
for number in range (1,11):
aList += [number]
print ("printing",aList);
Output is: printing [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
but if I modify like this (I expect 100 to be added to the end of the list)
aList = []
for number in range (1,11):
aList += [number]
aList += 100;
print ("printing",aList);
I get this error: TypeError: 'int' object is not iterable
You have three problems with your current code:
aList += 100
should be aList += [100]
aList += [100]
should be moved to outside the for loop For example:
In [2]:
aList = []
for number in range (1,11):
aList += [number]
aList += [100]
print ("printing",aList) # ('printing', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100])
You could also simply this to:
print ("printing", range(1, 11) + [100]) # ('printing', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100])
If you don't want to use .append()
on a list:
aList = []
for number in range (1,11):
aList += [number]
aList += [100]
print ("printing",aList)
Please note that you don't need the semicolon at the end of the line ( ;
)
range returns a list, hence this much is sufficient instead of for loop
aList = range(1, 11)
to add '100' as last element, add one more statement
aList += [100]
or
aList.append(100)
range
is a list. Hence, you can just do:
aList = range(10) + [100]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.