I have this simple code
n=[1,2,3,4,5,6,7,8]
for i in n:
x=i+5
print (x)
the answer will be like this
5
6
7
8
9
10
11
12
the question is:
how can i make python return the answer in a list like this [5,6,7,8,9,10,11,12]
??
You can declare a list
new_list = []
and inside the loop, use append()
method to add the element:
for i in n:
x = i + 5
new_list.append(x)
You can also do this by list comprenhension :
new_list = [i + 5 for i in n]
Using list comprehension is quite simple:
n=[1,2,3,4,5,6,7,8]
result = [i+5 for i in n]
print(result)
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.