+ 2

Different list-makin in Python: list() vs []

#both structures works well: print([i for i in range(10)]) print(list(i for i in range(10))) #BUT........I Have Some Strange Result: #for both of them input is: 0 1 2 3 4 5 6 7 8 9 print(list(map(int,input().split()))) print([map(int,input().split())]) #So what a difference between them? You may run it here: https://code.sololearn.com/cjDu75gBAh1K

22nd Sep 2018, 3:59 PM
dimon2101
dimon2101 - avatar
5 Respuestas
+ 3
(i for i in range(10)) is a generator object. Usually, it won't return anything until you "call" the single values with next() or with a for each loop: a = (i for i in range(10)) print(type(a)) #output: <class 'generator'> print(next(a)) #output: 0 print(next(a)) #output: 1 print(next(a)) #output: 2 for n in a: print(n) #output: 3, 4, 5 etc. If you use list(i for i in range(10)), you force the generator object to generate all values so that they can be put in a list. So this is actually a relatively complex way to create a list. [i for i in range(10)] is a list comprehension and is usally considered the "pythonic" way to create a list.
22nd Sep 2018, 4:37 PM
Anna
Anna - avatar
+ 2
@Julian Second one gives map object, not a list...
22nd Sep 2018, 4:39 PM
dimon2101
dimon2101 - avatar
+ 2
dimon2101 yeah but that one wasn't in the question so i didn't think he/she was talking about that
22nd Sep 2018, 4:40 PM
Julian
Julian - avatar
+ 1
there pretty much isn't really a big differance.
22nd Sep 2018, 4:35 PM
Julian
Julian - avatar
+ 1
@Anna Thank you for nice answer!!! I feel some confusing...
22nd Sep 2018, 4:46 PM
dimon2101
dimon2101 - avatar