質問

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top