Can I concatenate and append the result in a single statement?

I think it work with instead of ().

You can use list comprehension to solve this problem. To concatenate, we just simply use the + operator and to do this in one line, use list comprehension.

Here is what I did:

def add_greetings(names):

new_list = ["Hello, " + name for name in names]

return new_list

the error has occurred in your list name (greet_with name). you can have this name due to whitespace.
to fix this error correct the list name

1 Like

I really thought I had list comprehension this time :pensive:

What’s wrong with this answer? Why is it invalid syntax?

def add_greetings(names):
    lst = []
    lst.append("Hello, " + name) for name in names
    return lst

print(add_greetings(["Owen", "Max", "Sophie"]))

It’s invlaid syntax because there’s nothing to tell the interpreter that there’s a list comprehension. See the example below for a simple one and the docs for the full details-
https://docs.python.org/3/tutorial/datastructures.html#tut-listcomps

If it’s actually list comprehension you’re aiming for the .append method (and indeed most expressions with side effects) are not ideal to use with it.

A quick example of list comprehension (creating a list of numbers 1 to 10)-

# for loop style
lst = []
for x in range(1 ,11):
    lst.append(x)

# as a list comprehension...
[x for x in range(1, 11)]

My solution:

def add_greetings(names):

return [“Hello, {}”.format(name) for name in names]

lol i used this
#Write your function here

def add_greetings(names):

empty_list =

index = 0

while index < len(names):

greet = "Hello, " + names[index]

#print(greet)

empty_list.append(greet)

index += 1

return empty_list

print(empty_list)

#Uncomment the line below when your function is done

print(add_greetings([“Owen”, “Max”, “Sophie”]))

I see your comment was 4 months ago. Not sure if you are still coding or not but the best thing I have found that works when learning something you don’t understand is to keep doing it and researching it. It is time consuming I know but it works. IDK how much time I’ve spent on loops the past week but I would read as much as I can and look at code and breakdowns of the codes until I gained a certain understanding for it. Now that I’m doing the challenges again it’s coming to me a little more naturally.

@enghosamokasha
Why you used range in loop ?

I can’t remember, but it’s just a solution by using indexes to loop through the list and sure you can do it in many ways
example:

def add_greetings(names):
  return ["Hello, " + name for name in names]
  
 
print(add_greetings(["Owen", "Max", "Sophie"]))
#['Hello, Owen', 'Hello, Max', 'Hello, Sophie']