+ 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?

16th Jun 2022, 8:25 AM
Sasan Jafari
Sasan Jafari - avatar
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>
16th Jun 2022, 9:35 AM
Lothar
Lothar - avatar
+ 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)
16th Jun 2022, 10:00 AM
Sasan Jafari
Sasan Jafari - avatar
+ 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)
16th Jun 2022, 2:42 PM
AĶ¢J
AĶ¢J - avatar
+ 5
Append value in list Or use lambda expression to filter data as a list or use list comprehensions
16th Jun 2022, 8:38 AM
AĶ¢J
AĶ¢J - avatar
+ 5
alist = list(("apple", "banana", "cherry")) print(alist)
16th Jun 2022, 8:40 AM
JaScript
JaScript - avatar
+ 3
AĶ¢J thank you so much It is much easier
16th Jun 2022, 2:51 PM
Sasan Jafari
Sasan Jafari - avatar
+ 2
Create an empty list in another variable, append to it each even number
16th Jun 2022, 5:13 PM
Stefan Corneteanu
Stefan Corneteanu - avatar
0
I have no idea
18th Jun 2022, 4:30 AM
Kaleb Wald
Kaleb Wald - avatar