Lesson 25 of 55
15 mins readPython Introduction to Generics
In Plain English
Generics allow you to create functions, classes, and interfaces that work over a variety of types rather than a single one, while preserving full type safety.
Core Rules to Remember

Type Parameters: Enables capturing argument types dynamically with <T>.

Type Preservation: Retains specific member methods without falling back to any.
Live Interactive Example
Hit Run Code to see it liveWriting Generic Identity and Wrapper Functions
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: TypeScript infers T as number for numBox and T as string for strBox.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build a Generic Array First-Item Selector
Write a generic function getFirst<T>(items: T[]): T | undefined that returns items[0].
Call getFirst with [10, 20, 30] and ["apple", "banana"] and print both results separated by " | ".
1
2
3
4
5
6
7
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.