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?
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)))
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.
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
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.