python 3: lists dont change their values -


so trying change bunch of list items random percentage using loop.

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

(also dont how paste multiple lines of code did them 1 one, appreciate too) , when prints list consists of numbers started with.

your item =.... line, stands, associates new object name item in function's namespace. there no reason why operation change content of list object previous value of item extracted.

here listing changes list in-place:

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

the lyst[i] =... assignment key line changes list's content. of course can collapse 2 assignments 1 line if want: lyst[i] = item =..... or can omit reassignment item if you're not going use again in loop: lyst[i] = item + item *...

note performed 2 minor fixes in addition: changed variable name list lyst doesn't overshadow builtin reference list class. have altered function takes list object argument, rather relying on referring using hard-coded global variable name. both of these practice; nothing problem.

finally, note can of more succinctly , transparently so-called list comprehension. if don't have modify list in-place, i.e. if it's ok end modified copy of original list:

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

if need modify list in-place (e.g. if other references original list exist elsewhere , they, too, should point updated content after change() called) can follow suggestion in padraic's comment:

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

in last case, can save memory (which concern large lists) if change bracket shape , thereby use generator expression instead:

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

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -