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 ?
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]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With