Python Lists: A Simple Introduction for Beginners
What Is a List in Python?
A list is an ordered collection of objects. Objects can be Integer objects, Float objects, String objects, Boolean objects etc.
A list is written using square brackets [ ], and its objects are separated by commas.
For example:
numbers = [10, 20, 30, 40, 50]
Here:
numbersis the name referring to the list.[10, 20, 30, 40, 50]is the list object.- The list contains five integer objects.
- The objects appear in a particular order.
Array vs Python List
C / C++ / Java
• Arrays generally store elements of the same data type.
• Array size is usually fixed after creation.
• Arrays are mainly used to store a collection of values of a specific type.
• Example: int marks[5];
Python List
• A list can contain objects of different data types.
• A list can grow or shrink after creation.
• Lists are ordered and mutable collections of objects.
• Example: marks = [85, 72, 91, 68, 77]
Small technical note: The comparison is intentionally simplified for beginners. C++ and Java have additional dynamic collection types, and C/C++ arrays have some differences from each other.
Why Do We Need Lists?
Consider a program that needs to store the marks of 100 students.
Creating 100 separate variables would be inconvenient:
Instead, we can store all the marks in one list:
The main purpose of a list is therefore to organize and store multiple objects together.
Lists are commonly used for:
- marks of students
- names of students
- prices of products
- temperatures
- ages
- measurements
- sensor readings
Creating a List
The simplest way to create a list is:
This creates an empty list.
We can also create a list containing objects:
Another example: