I'm trying to replace the values in a list, but it doesn't work

Question:

i shortened the list

countries_list = [' USA', ' Russia', ' Japan', ' USA', ' China', ' China', ' Kazakhstan', ' USA', ' Shahrud Missile Test Site', ' China', ' Kazakhstan', ' USA', ' China']
for z in countries_list:
  if z == " Russia":
    z.replace("Russia","Russian Federation")

  elif z == "New Mexico":
    z.replace(" New Mexico","USA")

  elif z == "Yellow Sea":
    z.replace(" Yellow Sea","China")

  elif z == "Shahrud Missile Test Site":
    z.replace(" Shahrud Missile Test Site","Iran")

  elif z == "Pacific Missile Range Facility":
    z.replace("Pacific Missile Range Facility","USA")

  elif z == "Barents Sea":
    z.replace("Barents Sea","Russian Federation")

  elif z == "Gran Canaria":
    z.replace("Gran Canaria","USA")

print(countries_list)

after printing, the russia and Shahrud Missile Test Site value doesn’t change. help

Asked By: tunji

||

Answers:

The .replace function does not modify the string in place. you would need to reassign the value to the list for this to work.

I suggest changing the for loop to be a for in range loop and implementing it as below.

for i in range(len(countries_list)):

    if countries_list[i] == "country_name":
        countries_list[i] = countries_list[i].replace("country_name", "new_country_name")
    # ...
Answered By: HPringles

Since Python strings are immutable, none of the string methods are in-place.

In essence, all the calls to .replace create a new string and throw it away.

You need to iterate using the indexes so you can call .replace and assign it back:

countries_list = [' USA', ' Russia', ' Japan', ' USA', ' China', ' China', ' Kazakhstan', ' USA', ' Shahrud Missile Test Site', ' China', ' Kazakhstan', ' USA', ' China']
for index, country in enumerate(countries_list):
    if country == " Russia":
        countries_list[index] = country.replace('Russia', 'Russian Federation')
    ...
Answered By: DeepSpace

As mentioned in the other answers, when using ‘replace’, you need to write the value back to the list, or perhaps to a new list.

countries_list = [' USA', ' Russia', ' Japan', ' USA', ' China', ' China', ' Kazakhstan', ' USA', ' Shahrud Missile Test Site', ' China', ' Kazakhstan', ' USA', ' China']

for x in range(len(countries_list)):
  if countries_list[x] == ' Russia':
    countries_list[x] = 'Russian Federation'
  elif countries_list[x] == ' New Mexico':
       countries_list[x] = 'USA'
  # etc. etc.

print(countries_list)

I think it’s also worth suggesting this alternative approach that uses a dictionary to look up the countries instead of several if/elif clauses:

countries_list = [' USA', ' Russia', ' Japan', ' USA', ' China', ' China', ' Kazakhstan', ' USA', ' Shahrud Missile Test Site', ' China', ' Kazakhstan', ' USA', ' China']

updated_list = []

replace_with = {
  'Russia':'Russian Federation',
  'New Mexico': 'USA'
  # etc. etc.
}
for x in range(len(countries_list)):
  this_entry = countries_list[x].strip() # remove the leading spaces
  if this_entry in replace_with:
    updated_list.append( replace_with[this_entry] )
  else:
    updated_list.append( this_entry )
  # etc. etc.

print(updated_list)

Answered By: PangolinPaws

Other people have told you why this doesn’t work. It might be more manageable to avoid a long list of ifs and else and use a dict.
You can then make a new list with the values updated like this:

def replacer(countries):
     lookup = {"Russia" : "Russian Federation"}
     # add more entries for other swaps here
     for country in countries:
         yield lookup.get(country, country)

You can then make a new list like this:

list(replacer(countries_list))
Answered By: doctorlove

you need use for sentence with index and item to replace the value in the list, in you code yo try change the value in the z object, this is change but not in the list. I hope this code help you.

countries_list = [' USA', ' Russia', ' Japan', ' USA', ' China', ' China', ' Kazakhstan', ' USA', 'Shahrud Missile Test Site', ' China', ' Kazakhstan', ' USA', ' China']
for index, item in enumerate(countries_list):
    if item == " Russia":
        countries_list[index] = "Russian Federation"
    elif item == "New Mexico":
        countries_list[index] ="USA"

    elif item == "Yellow Sea":
        countries_list[index] ="China"

    elif item == 'Shahrud Missile Test Site':
        countries_list[index] = "Iran"

    elif item == "Pacific Missile Range Facility":
        countries_list[index] ="USA"

    elif item == "Barents Sea":
        countries_list[index] ="Russian Federation"

    elif item == "Gran Canaria":
        countries_list[index] ="USA"
print(countries_list)
Answered By: Marcos Riveros
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.