If your aim is to change an immutable value in some way, this would be best:
def add_one(value):
return value + 1
def main():
# your code moved to a function, to avoid these variables inadvertently becoming globals
item = 1
# update item with the function result
item = add_one(item)
print("item is => ", item)
if __name__ == '__main__':
main()
From your example, it appears you want to update a list with each item in the list incremented by 1, you can do that the same way:
def add_one_all(values):
return [values + 1 for values in values]
def main():
items = [1, 4, 9]
# update items with the function result
items = add_one_all(items)
print("items are => ", items)
if __name__ == '__main__':
main()
However, since a list is mutable, you can update it from inside a function, by making the changes to the list in-place:
def add_one_all_inplace(values: list = None):
if values is not None:
for i in range(len(values)):
values[i] += 1
def main():
items = [1, 4, 9]
# update the content of items
add_one_all_inplace(items)
print("items are => ", items)
if __name__ == '__main__':
main()
The advantage of the latter solution is that no new list is created, which may be preferable if you need to be very frugal with space, or are only making a few changes to a very large list - your example would probably be better served with the second solution though.
Note that the way you called the function still wouldn't work in the latter case:
def main():
item = 1
add_one_all_inplace([item])
The list containing item would be changed to be [2], but that doesn't affect item itself. The list passed to add_one_all_inplace will just contain the value of item, not a reference to it.
itemthat way. Putting a variable into a list puts the value of variable, it doesn't put a reference to the variable itself.arris modified in the function, but since item is a simple immutable integer, it can't be modified inside the function, unless you declareitema global and that's not really what you want. (in fact, your code would be improved if you called a functionmain()or whatever from theif __name__section, instead of having the code in there, to avoid all the variable getting declared there effectively becoming globals.)