1

I am finding it difficult to understand how the following code works:

mylist = [1,2,3,4,5]
print(sum(i for i in mylist))

the code above gives a correct result of 15, but shouldn't "i" be used after it is declared and not before?

abunickabhi
5882 gold badges11 silver badges32 bronze badges
asked Aug 20, 2018 at 9:24
3
  • What you see is — despite the name for — not a for loop, but a (generator) comprehension. Like some other special expressions (e.g. ternary if: x = 3 if foo=bar else 5) it has this "weird" order, because that's how you would say it in English. Commented Aug 20, 2018 at 9:27
  • 3
    @RobJan Nit-picking here, but: No, that's not a list comprehension Commented Aug 20, 2018 at 9:27
  • @L3viathan I admit that this is way to create generator. Commented Aug 20, 2018 at 9:45

4 Answers 4

4

Read the documentation on generator expressions.

You will see that you are (effectively) creating a mini generator equivalent to:

def iter_list(lst):
 for i in lst:
 yield i
myList = [1,2,3,4,5]
print(sum(iter_list(myList)))
answered Aug 20, 2018 at 9:27
Sign up to request clarification or add additional context in comments.

Comments

1

Python is an untyped language. That means you do not need to declare the variables such as i.

You can give a bit more clarity to compiler , and your understanding by doing the edit:

mylist = [1,2,3,4,5]
print(sum(int(i) for i in mylist ))

So, Python is just very smart in giving type to variables, and flexible too as compared to static C code.

answered Aug 20, 2018 at 9:28

Comments

1

In this particular case (list-compherensions) the syntax allows to do so

answered Aug 20, 2018 at 9:29

Comments

1

Because of the Syntax of sum() ... iterable and a start position

sum(i, start)

You can take an look with examples there --> https://www.programiz.com/python-programming/methods/built-in/sum

answered Aug 20, 2018 at 9:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.