Reputation: 33
Trying to add 5 to tuple elements using loop and list.
t=(10,20,30,40,50)
lst = []
for i in t:
lst[i]=t[i]+5
t = tuple(lst)
print(t)
Upvotes: 3
Views: 47
Reputation: 92440
Python discourages using indices this way unless you really need them. When you write for i in t:
, i
will be the values of t
not the indices, so t[i]
is probably not what you want — that will be t[10]
, t[20]
, etc...
The pythonic way is to use a comprehension:
t=(10,20,30,40,50)
t = tuple(n + 5 for n in t)
print(t)
# (15, 25, 35, 45, 55)
If you really want to use a loop, you can just append to the list as you go:
t=(10,20,30,40,50)
lst = []
for n in t:
lst.append(n+5)
t = tuple(lst)
print(t)
# (15, 25, 35, 45, 55)
Upvotes: 6