python - creating a new list by copying from an old list -


this first post here, please excuse me if not make myself clear. searched problem beforehand, didn't know terms phrase in. code part of larger program, tried cutting out other variables , problem still remains:

what want create function categorizes list of numbers in 7-number sublists. there must 1 sublist each item in 'player' list, why copied player list , ran loop replace each element (previously names of players) corresponding 7 numbers. number of sets there should drawn 'player' list, , numbers drawn 'playermodifier' list, both of defined elsewhere in program.

players=['paul', 'darren'] playermodifiers=[4,5,7,2,8,4,7,3,9,4,6,2,6,4] def modifiersort():     n=1     global playermodifierssort     global playermodifiers     playermodifierssort=players     x in playermodifierssort:         playermodifierssort[n-1]=playermodifiers[7*(n-1):7*n]         n=n+1     playermodifiers=playermodifierssort 

this sorts list want to, however, somehow changes original 'players' list identical playermodifierssort , playermodifiers @ end of function. when run function, get:

playermodifiers = [[4, 5, 7, 2, 8, 4, 7], [3, 9, 4, 6, 2, 6, 4]] players = [[4, 5, 7, 2, 8, 4, 7], [3, 9, 4, 6, 2, 6, 4]] 

this problematic because want preserve players list. how can happening? 'players' list isn't global, how can permanently changed result of function?

your line

playermodifierssort=players 

is not copying values of players playermodifierssort; it's making playermodifierssort reference players. thus, changes playermodifierssort change players. replace line with:

playermodifierssort=players[:] 

to copy values of list , you'll fine.


addendum: see this article regarding list copying (reference vs. value). also, you'll need fix playermodifiers=playermodifierssort line has same problem. not copying values -- making playermodifiers reference playermodifierssort.

another question might of use you.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -