A
A
albertalexandrov2018-06-15 17:57:34
Python
albertalexandrov, 2018-06-15 17:57:34

Generator or list?

Hello!
There is a task to calculate the sum of digits in a string. The number is passed as an argument. The question is this. As it is preferable to do - by converting a string of numbers into a generator or a list:

import sys

print(sum((int(x) for x in sys.argv[1])))  # генератор

или

print(sum([int(x) for x in sys.argv[1]]))  # список

I would choose the first option.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Romanov, 2018-06-15
@albertalexandrov

In almost any case, it is better to use generators, as they allow you not to store or calculate unnecessary data. Lists need to be formed only when one pass is not enough.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question