Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing values from loop in a list or tuple in Python

Tags:

python

Im very new to python and playing around with loops and stuck on a basic doubt

Im trying to perform the following:

tup1=()
for i in range(1,10,2):
 tup1=(tup1,i)
print tup1

I expect the out put to be the sequence 1 to 10. However i end up with the following:

((((((), 0), 2), 4), 6), 8)

Could you please help me as to if this approach is correct or are there better ways to meet the requirement ?

like image 975
abhishek nair Avatar asked Nov 05 '15 19:11

abhishek nair


2 Answers

If you just want an iterable with the even numbers 1 to 10 then the simplest way to do it:

seq = range(2, 11, 2)

If you are doing this as a means of learning Python and you want to build up your own data structure, use a list:

l = []
for i in range(2, 11, 2):
    l.append(i)

The above for loop can be rewritten as a list comprehension:

l = [i for i in range(2, 11, 2)]

or using an if clause in the loop comprehension:

l = [ i for i in range(1, 11) if i % 2 == 0]
like image 158
chucksmash Avatar answered Nov 10 '22 14:11

chucksmash


You can append an item to a tuple using the += operator.

tup1=()
for i in range(1,10,2):
   tup1+= (i,)
print tup1

This prints (1, 3, 5, 7, 9)

like image 45
rfloresx Avatar answered Nov 10 '22 14:11

rfloresx