w3resource

Python: Display the first and last colors from a given list

Python Basic: Exercise-8 with Solution

Write a Python program to display the first and last colors from the following list.

color_list = ["Red","Green","White" ,"Black"]

Pictorial Presentation:

Display the first and last colors from a given list

Sample Solution:

Python Code:

# Create a list called 'color_list' containing color names
color_list = ["Red", "Green", "White", "Black"]
# Print the first and last elements of the 'color_list' using string formatting
# The '%s' placeholders are filled with the values of 'color_list[0]' (Red) and 'color_list[-1]' (Black)
print("%s %s" % (color_list[0], color_list[-1]))

Sample Output:

Red Black

Explanation:

The said code creates a list named "color_list" which includes four different colors, "Red", "Green", "White", and "Black". Then, it utilizes string formatting to print the first (Index 0) and the last (Index -1) color of the list together with a space in between. The output would be "Red Black".

Flowchart:

Flowchart: Display the first and last colors from a given list.

Python Code Editor:

 

Previous: Write a Python program to accept a filename from the user and print the extension of that.
Next: Write a Python program to display the examination schedule. (extract the date from exam_st_date).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-8.php