Add Variables to Tuple Using list looping

Asish :

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)
Mark Meyer :

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=293253&siteId=1