Return the First Element in a List
Quick Overview
`lst[0]` raises `IndexError` on an empty list, where `lst[:1]` quietly returns an empty list. Negative indices count from the end, making `lst[-1]` the last element.
Deep Dive
1. The Challenge: List Indexing
Create a function get_first_value(number_list) that takes a list containing numbers and returns the first element.
2. Why It Matters
Lists are Python's primary ordered collection data type. Accessing elements by 0-based index is an essential skill.
3. The Python Solution
Use zero-based index [0]:
def get_first_value(number_list):
return number_list[0]
# Testing our function
print(get_first_value([1, 2, 3])) # Output: 1
print(get_first_value([80, 5, 100])) # Output: 80
print(get_first_value([-500, 0, 50])) # Output: -500
4. Understanding Python List Indexing
list[0]: First element.list[1]: Second element.list[-1]: Last element (negative indexing counts from the end!).
5. Common Mistakes
- IndexError on Empty Lists: Accessing
list[0]on an empty list[]raises an uncaughtIndexError: list index out of range. Handle empty lists safely:if not number_list: return None.
6. Next Steps
Use [0] for the first element and [-1] for the last element. Next, let's convert strings to integers and vice versa!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.