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)
Tuples are immutable objects in Python. Thus means you can't modify them. What you're doing right now is creating a new tuple with the previous one inside
You could do:
lst = []
for i in range(1,10,2):
lst.append(i)
tup = tuple(lst) #If you really want a tuple
print tup
But lst = range(1,10,2)
or tup = tuple(range(1,10,2))
is much better (Unless you want to use append for some reason)
Read about List Comprehension
tuple(i for i in range(1, 10, 2))
Or
tup1 = ()
for i in range(1, 10, 2):
tup1 += (i,)
print tup1
它是这样的:
print range(1, 11)
You are skipping by two by using for i in range(1,10,2):
if you use for i in range(1,11):
if will increment by 1. As for tup1=(tup1,i)
you are constantly adding a tuple to each other which is creating the weird output. You could use a list if you want to store them. Otherwise using will do it just fine:
print(range(10))
List item
For appending into list or tuple you can use append() function or you can use += operator which does the same. s=()
for i in range(1,11): s+=(i,)
print(s) #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
x=()
for i in range(1,11,2): x+=(i,)
print(x) #odd nos from 1-9 (1, 3, 5, 7, 9)
x=()
for i in range(2,11,2): x+=(i,)
print(x) #even nos from 2-10 (2, 4, 6, 8, 10)
Storing values from loop in a list or tuple in Python by following ways -
-> By appending the value in the list (here new_data1) as join will not work here.
new_data1 = []
for line in all_words:
new_data=' '.join(lemmatize_sentence(line))
new_data1.append(new_data)
#print (new_data)
print (new_data1)
PS - This is just a snapshot of a code just for hint . Hope this helps!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.