python 3: lists dont change their values

2024/11/18 3:41:33

So I am trying to change a bunch of list items by a random percentage using a for loop.

import random as rdm
list = [1000, 100, 50, 25]
def change():for item in list:item = item + item*rdm.uniform(-10, 10)
change()
print(list)

(also I dont get how to paste multiple lines of code so I did them one by one, would appreciate help with that too) And now when it prints the list it only consists of the numbers it started with.

Answer

Your item =.... line, as it stands, just associates a new object with the name item in the function's namespace. There is no reason why this operation would change the content of the list object from which the previous value of item was extracted.

Here is a listing that changes a list in-place:

import random
lyst = [1000,100,50,25]
def change(lyst):for i, item in enumerate(lyst):item = item + item * random.uniform(-10, 10)lyst[i] = itemprint(lyst)
change(lyst)
print(lyst)

The lyst[i] =... assignment is the key line that actually changes the list's content. Of course you can collapse the two assignments into one line if you want: lyst[i] = item =..... Or you can omit the reassignment to item if you're not going to use it again in the loop: lyst[i] = item + item *...

Note that I performed two minor fixes in addition: I changed the variable name from list to lyst so that it doesn't overshadow your builtin reference to the list class. I have also altered your function so that it takes the list object as an argument, rather than relying on referring to it using a hard-coded global variable name. Both of these are just good practice; nothing to do with your problem.

Finally, note that you can do all of this much more succinctly and transparently with a so-called list comprehension. If you don't have to modify the list in-place, i.e. if it's OK to end up with a modified copy of the original list:

lyst = [ item + item * random.uniform(-10, 10)  for item in lyst ]

If you need to modify the list in-place (e.g. if other references to the original list exist elsewhere and they, too, should point to the updated content after change() is called) then you can follow the suggestion in Padraic's comment:

lyst[:] = [ item + item * random.uniform(-10, 10)  for item in lyst ]

In that last case, you can even save memory (which will only be a concern for very large lists) if you change the bracket shape and thereby use a generator expression instead:

lyst[:] = ( item + item * random.uniform(-10, 10)  for item in lyst )
https://en.xdnf.cn/q/120120.html

Related Q&A

Using zip_longest on unequal lists but repeat the last entry instead of returning None

There is an existing thread about this Zipping unequal lists in python in to a list which does not drop any element from longer list being zipped But its not quite Im after. Instead of returning None, …

python scrapy not crawling all urls in scraped list

I am trying to scrape information from the pages listed on this page. https://pardo.ch/pardo/program/archive/2017/catalog-films.htmlthe xpath selector:film_page_urls_startpage = sel.xpath(//article[@cl…

Python - Do (something) when event is near [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Python script to find nth prime number

Im new to Python and I thought Id try to learn the ropes a bit by writing a function to find the nth prime number, however I cant get my code to work properly. No doubt this is due to me missing someth…

Printing values from list within an input range

I have an unordered list, lets say:lst = [12,23,35,54,43,29,65]and the program will prompt the user to input two numbers, where these two numbers will represent the range.input1 = 22input2 = 55therefor…

An issue with the tag add command of the ttk.Treeview widget - cant handle white space

I have noticed an issue with using the tag add command of a ttk.Treeview widget when activated with the tk.call() method. That is, it cant handle white space in the value of the str() elements of its i…

How to show the ten most overdue numbers in a list

I have asked a question before about this bit of code and it was answered adequately, but I have an additional question about showing the ten most overdue numbers. (This program was a part of an in-cla…

Connect a Flask webservice from a device which is not on the same network

I am not an expert in web programming and know very little about it. I am trying to run a webservice on an EC2 instance (Windows Server 2012R2) and the webservice is written in Python using Flask packa…

why int object is not iterable while str is into python [duplicate]

This question already has answers here:Why is int" not iterable in Python, but str are?(4 answers)Closed 2 years ago.As i know we can not iterate int value while we can iterate strings in python.…

an irregular anomaly in python tuple

i create two identical tuples and use is operator on them the answer that should come is false but when i use it in vscode/atom/notepadd++ it comes true but when i use the same code in pthon run throug…