+ 2
how to make a list?
i had one practice which gave me a list of numbers and asked for a list for even numbers i wrote this: a = [1, 4, 9, 16, 25, 36, 38, 49, 54, 63, 64, 81, 100] for i in a: if i%2==0: print(i) I forgot how to make a list as an output can anyone help?
8 Answers
+ 7
Sasan Jafari ,
take your code and modify it:
- before going in the loop, create an empty list e.g. <res>
- inside the loop, remove or comment out the print statement
- instead of print, use the new list <res> and the list method <.append(<argument>)>, where argument is the current item in loop => i
- after loop is finished, print out the new list <res>
+ 6
@lothar @JaScript @AĶ¢J
thank you guys, I solved the problem
a = [1, 4, 9, 16, 25, 36, 38, 49, 54, 63, 64, 81, 100]
new_list = []
for i in a:
if i%2==0:
new_list.append(i)
print(new_list)
+ 6
Sasan Jafari
Using list comprehension
a = [1, 4, 9, 16, 25, 36, 38, 49, 54, 63, 64, 81, 100]
new_list = [i for i in a if i % 2 == 0]
print (new_list)
+ 5
Append value in list
Or use lambda expression to filter data as a list
or use list comprehensions
+ 5
alist = list(("apple", "banana", "cherry"))
print(alist)
+ 3
AĶ¢J thank you so much
It is much easier
+ 2
Create an empty list in another variable, append to it each even number
0
I have no idea