user14920798
user14920798

Reputation:

Beginner Python - Printing Values in a List

I am new to Python, and I am making a list. I want to make a print statement that says "Hello" to all the values in the lists all at once.

    Objects=["Calculator", "Pencil", "Eraser"]
    print("Hello " + Objects[0] + ", " + Objects[1] + ", " + Objects[2])

Above, I am repeating "Objects" and its index three times. Is there any way that I can simply write "Objects" followed by the positions of the values once but still get all three values printed at the same time?

Thanks

Upvotes: 0

Views: 67

Answers (3)

Beesho
Beesho

Reputation: 1

Not sure this is the most elegant way but it works:

strTemp = ""
for i in range(len(Objects)):
    strTemp += Objects[i] + " "
print ("Hello " + strTemp)

Start with an empty string, put all the values in your list in that string and then just print a the string Hello with your Temporary String like above.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881353

You can use the string join function, which will take a list and join all the elements up with a specified separator:

", ".join(['a', 'b', 'c']) # gives "a, b, c"

You should also start to prefer f-strings in Python as it makes you code more succinct and "cleaner" (IMNSHO):

Objects = ["Calculator", "Pencil", "Eraser"]
print(f"Hello {', '.join(Objects)}")

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

You could use join() here:

Objects = ["Calculator", "Pencil", "Eraser"]
print('Hello ' + ', '.join(Objects))

This prints:

Hello Calculator, Pencil, Eraser

Upvotes: 1

Related Questions