Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do replace a list with another list in python?

Tags:

python

list

I am making a hangman game and I want to be able to replace the list of original words with a list of new words typed in by the user. At the minute my code is this:

gamewords[:] = newgamewords[:]

But this does not seem to work...

The original list is this:

gamewords= ['blue','violet','red','orange','fuchsia','cyan','magenta','azure','black','turquoise','pink','scarlet']

A word is then chosen for the list randomly

 word=gamewords[random.randint(0,len(gamewords)-1)]

i want to change it so that the word is chosen from the new list, how do i do this?

like image 409
CP beginner Avatar asked May 28 '26 14:05

CP beginner


2 Answers

You probably meant to do this:

gamewords = newgamewords[:]  # i.e. copy newgamewords

Another alternative would be

gamewords = list(newgamewords)

I find the latter more readable.


Note that when you 'copy' a list like both of these approaches do, changes to the new copied list will not effect the original. If you simply assigned newgamewords to gamewords (i.e. gamewords = newgamewords), then changes to gamewords would effect newgamewords.


Relevant Documentation

  • list
like image 123
arshajii Avatar answered May 31 '26 06:05

arshajii


I'm not sure what you exactly want. There are two options:

  1. gamewords = newgamewords[:]
  2. gamewords = newgamewords

The difference is that the first option copies the elements of newgamewords and assigns it to gamewords. The second option just assigns a reference of newgamewords to gamewords. Using the second version, you would change the original newgamewords-list if you changed gamewords.

Because you didn't give more of your source code I can't decide which will work properly for you, you have to figure it out yourself.

like image 20
George Avatar answered May 31 '26 05:05

George