+ 1

Just a doubt!

Hello everyone! How are you? I'm learning phyton and I've some questions. How can I "decide" which of this methods is better suited, runs faster and it's more "phytonical" correct? # Get 10 numbers from a user and sum them. 1) list=[] for i in range(10): list.append(int(input("Enter a number: "))) print(sum(list)) 2) sum=0 for i in range (10): number = int(input("Enter a number: ")) sum += number print(sum)

27th Jan 2021, 1:09 PM
Lucio Fontana
Lucio Fontana - avatar
7 Answers
+ 3
Both works, both are pythonic, and both are just the same since when you run your number (1), number(2) is happening in the background. In other words when you use "sum" function, there is an iteration happening in the background similar to your second snippet.
27th Jan 2021, 4:49 PM
noteve
noteve - avatar
+ 3
speed has not to be considered, as the loop is asynchronous related to user input (and even speed difference would be unuseful and micro-optimisation).
27th Jan 2021, 7:55 PM
visph
visph - avatar
+ 2
The solution from Abol is very concise and pythonic although I wonder what Allah has to do with it. To understand it, read about List comprehension. At this level you shouldn't worry about runtime performance. Instead focus on clean and readable code. If you want to use the numbers for something else, consider this variant: numbers = [int(input()) for _ in range(10)] print(sum(numbers))
27th Jan 2021, 2:42 PM
Benjamin JĂŒrgens
Benjamin JĂŒrgens - avatar
0
Discuss teaching and learning methods
27th Apr 2024, 9:11 PM
Buhle Gumevu
Buhle Gumevu - avatar