Search code examples
pythonpython-3.x

How can I exchange two elements in a python list?


I didn't really find any solution because "swap", "change" and "exchange" are really overloaded words. I am still in the beginning phase of learning and trying to exchange the words "empty" and instead let it insert the parameter behind "add_city".

cities = ["Tokio", "empty", "Berlin", "Accra", "empty"]

def add_city(article):
    for article in cities:
        if article == "empty":
            article = cities[1]
            cities.append(article)
            break
print(cities)



add_city("Paris")

So in the end it should print out:

["Tokio", "Paris", "Berlin", "Accra", "empty"]

Can anyone give a quick guidance?


Solution

  • You can use index to do that:

    cities = ["Tokio", "empty", "Berlin", "Accra", "empty"]
    
    def add_city(city, cities):
        cities[cities.index('empty')] = city
        print(cities)
    
    add_city("Paris", cities)
    

    Index will return the index of the first appear of 'empty', and you simply fill that index with the city you pass.