Search code examples
python-3.xliststring-concatenation

Concatinating strings to list items using for loops in python


I am pretty new to python3, and lately, I have been practicing with lists and functions.

Here, I stored strings inside a list then passed that list to a function that is supposed to concatenate/add a string, like so:

def hello(names):
    for name in names:
        name = "Hello "+name+"!"
    return names


liiist = ["L Lawliet", "Nate River", "Mihael Keehl"]
liiist = hello(liiist)
print(liiist)

But instead of getting ['Hello L Lawliet!', 'Hello Nate River!', 'Hello Mihael Keehl!'], I just get ['L Lawliet', 'Nate River', 'Mihael Keehl'] Nothing happened. Also, PyCharm alerts me that Local variable 'name' value is not used

I also experimented with this problem, and it turns out, it also doesn't work outside of functions:

vars = ["trying", "to", "rewrite", "lists"]
for var in vars:
    var = var + " hello"
print(vars)

The output: ['trying', 'to', 'rewrite', 'lists']

I have already found a way around this problem, but I am not happy that I just found the solution by chance/massive amounts of trial and error. I think me not understanding why python produced results like these might interfere with my career later on. Can someone please explain why this happens?

Also, if you're curious, here is the work-around I found:

def hello(names):
    counter = 0
    for name in names:
        name = name + " the Great"
        names[counter] = names
        counter += 1
    return names

names = ["L Lawliet", "Nate River", "Mihael Keehl"]
names = hello(names)
print(names)

Giving me a more efficient code than the one above can also help :)


Solution

  • One way to get the above output is by appending to the list as mentioned above by @Andrej Kesely. Another way is to use 'yield' generator that outputs the sequence. Refer to the below code.

    def hello(names):
        for name in names:
            name = "Hello "+name+"!"
            yield name     # generator that outputs sequence. Yield should be inside loop
    
    liiist = ["L Lawliet", "Nate River", "Mihael Keehl"]
    liiist = list(hello(liiist))     # store the yield output in a list when calling the function
    print(liiist)
    

    Refer to the below snapshot for the output

    enter image description here