Working with Lists
This guide demonstrates common list operations through a practical example of managing student grades.Creating and Initializing Lists
Start by creating a list with initial values:Adding Elements
Add new elements to your list using theadd() method:
Displaying Lists
Print Entire List
You can print the entire list at once:Print Individual Elements
Use afor-in loop to iterate through each element:
The
for-in loop is ideal when you need to access each element but don’t need the index position.Calculating with Lists
Computing the Sum
Iterate through the list to calculate the total:Computing the Average
Divide the sum by the number of elements using thelength property:
Complete Example
Here’s a complete program that demonstrates list operations:Common List Operations
| Operation | Method/Property | Description |
|---|---|---|
| Add element | add(value) | Adds a single element to the end |
| Get size | length | Returns the number of elements |
| Iterate | for-in loop | Access each element sequentially |
| Access element | list[index] | Get element at specific position |
| Calculate | Loop + accumulator | Sum, average, or other calculations |
Practical Use Cases
Grade Management
Store and calculate student grades, averages, and statistics
Data Collection
Accumulate data points for analysis and reporting
Inventory Tracking
Track quantities, prices, or stock levels
Score Keeping
Manage game scores, points, or rankings
Best Practices
Next Steps
Now that you understand basic list operations, you can:- Learn different ways to iterate through lists
- Explore advanced list methods like
map(),where(), andreduce() - Work with lists of custom objects
- Combine multiple operations for complex data processing