Type Hints Function in Python

Level 5232 keystrokes

This uses type hints to document function parameters and return type. Optional[int] means the return can be int or None.

Python code

# Import type hints from typing module
# List represents a list, Optional means value can be None
1from typing import List, Optional
2
# Type hints: nums is a list of int, returns int or None
3def find_max(nums: List[int]) -> Optional[int]:
# Handle empty list case - return None
4 if not nums:
5 return None
# Use built-in max() for non-empty list
6 return max(nums)
7
# Test with a list of numbers
8result = find_max([3, 1, 4, 1, 5])
9print(f"Max: {result}")
# Test with empty list - should return None
10result = find_max([])
11print(f"Empty: {result}")

Output

Max: 5
Empty: None
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 6
  • )× 6
  • ,× 5
  • :× 5
  • "× 4
  • [× 4
  • ]× 4
  • _× 3
  • {× 2
  • }× 2

More Python examples at level 5

← Python typing practice