Home > Enterprise >  trying to change string in a list in python via method and loop
trying to change string in a list in python via method and loop

Time:04-11

magician_names=('joker','Randell Flag','Bozo')
    def show_magicians(names):
        for i in names:
            print(i)
    def make_great(names):
        names[:] = ['the great ' str(names[i]) for i in names]
    make_great(magician_names)
    show_magicians(magician_names)

CodePudding user response:

You can try something like this :

def make_great(names):
    new_list=[]
    var = ['the great ' str(names[i]) for i in range(len(names))]
    new_list.append(var)
    return new_list

CodePudding user response:

If you are trying to return a tuple, maybe something like this could help. Like previous people have said, it would be good if you were more elaborate on your question as it is difficult to guess what you are asking.

def make_great(names):
    names = tuple([f'the great {str(i)}' for i in names])
    return names

CodePudding user response:

This would fix your code

magician_names=('joker','Randell Flag','Bozo')
def show_magicians(names):
    for i in names:
        print(i)
def make_great(names):
    names = [f'the great {i}' for i in names]
    print(names)
make_great(magician_names)
show_magicians(magician_names)

Your mistake was over here:

names[:] = ['the great ' str(names[i]) for i in names]

i is already a string so you were calling a list using a string as its index.

  • Related