Tutorialspoint
Problem
Solution
Submissions

Extract the First and Last Elements of a List

Certification: Basic Level Accuracy: 61.31% Submissions: 168 Points: 5

Write a Python program that extracts the first and last elements of a given list.

Example 1
  • Input: [1, 2, 3, 4, 5]
  • Output: [1, 5]
  • Explanation:
    • Step 1: Get the first element of the list [1, 2, 3, 4, 5], which is 1.
    • Step 2: Get the last element of the list [1, 2, 3, 4, 5], which is 5.
    • Step 3: Create a new list containing these two elements: [1, 5].
    • Step 4: Return the new list [1, 5].
Example 2
  • Input: ["apple"]
  • Output: ["apple", "apple"]
  • Explanation:
    • Step 1: Get the first element of the list ["apple"], which is "apple".
    • Step 2: Get the last element of the list ["apple"], which is also "apple" since there is only one element.
    • Step 3: Create a new list containing these two elements: ["apple", "apple"].
    • Step 4: Return the new list ["apple", "apple"].
Constraints
  • 1 ≤ len(list) ≤ 10^6
  • Elements can be of any data type
  • Time Complexity: O(1)
  • Space Complexity: O(1)
ArraysListTutorialspointSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

 
  • Use indexing: [lst[0], lst[-1]]
  • Use list unpacking: first, *middle, last = lst; [first, last]
  • Handle single element lists: [lst[0], lst[0]] if len(lst) == 1 else [lst[0], lst[-1]]
  • Use list comprehension with conditions: [lst[i] for i in (0, -1 if len(lst) > 1 else 0)]

Here's the step-by-step solution to extract the first and last elements of a list:

  • Create a function called first_last_elements that accepts a list parameter lst.
  • Use list indexing to access the first element of the list: lst[0]
  • Use list indexing to access the last element of the list: lst[-1] (Python's way of accessing the last element)
  • Return both elements as a new list: return [lst[0], lst[-1]]
  • Call the function with the example list [1, 2, 3, 4, 5]
  • Print the result, which will be [1, 5]

Submitted Code :