5.7 Creating Lists (BT101CO)
In Python, a List is a versatile, ordered collection of items that can hold different data types (integers, strings, even other lists). Lists are mutable, meaning you can change their content after they are created.
1. Simple Assignment (Square Brackets)
The most common way to create a list is by placing comma-separated values inside square brackets [].
- Empty List:
my_list = [] - Homogeneous List (Same types):
numbers = [10, 20, 30, 40] - Heterogeneous List (Mixed types):
student = ["Ashok", 101, 85.5, True]
2. Using the list() Constructor
You can convert other "iterable" objects (like strings, tuples, or ranges) into a list using the built-in list() function.
- From a String:
chars = list("PYTHON")→['P', 'Y', 'T', 'H', 'O', 'N'] - From a Range:
nums = list(range(1, 6))→[1, 2, 3, 4, 5]
3. List Comprehension
List comprehension offers a shorter syntax to create a new list based on the values of an existing list or range. It combines a for loop and an optional if condition into one line.
Syntax: [expression for item in iterable if condition]
Example: Creating a list of squares
# Standard way
squares = []
for x in range(1, 6):
squares.append(x**2)
# List Comprehension way
squares = [x**2 for x in range(1, 6)]
# Result: [1, 4, 9, 16, 25]
4. Input-Based List Creation
In many programming problems, you need to create a list from user input. There are two common patterns for this:
A. Using a Loop and append()
n = int(input("How many items? "))
my_list = []
for i in range(n):
val = input(f"Enter item {i+1}: ")
my_list.append(val)
B. Using split() (Single Line Input)
If the user enters items separated by spaces (e.g., 10 20 30), you can capture them all at once.
data = input("Enter numbers separated by space: ").split()
# if input is "10 20 30", data becomes ['10', '20', '30']
5. Summary Table: List Creation Methods
| Method | Syntax Example | Best Used For... |
|---|---|---|
| Square Brackets | L = [1, 2, 3] | When you already know the items. |
list() Constructor | L = list(range(5)) | Converting other types to a list. |
| Comprehension | [x for x in L] | Transforming or filtering existing data. |
append() loop | L.append(x) | Building a list dynamically. |
Key List Properties to Remember
- Ordered: The items have a defined order that will not change.
- Indexed: You access items by their position (starting from 0).
- Mutable: You can add, remove, or change items.
- Dynamic: A list can grow or shrink in size as needed.