How to Create a List in Python: Syntax and Examples
To create a list in Python, use square brackets
[] and separate items with commas. For example, my_list = [1, 2, 3] creates a list of three numbers.Syntax
A list in Python is created by placing items inside square brackets [], separated by commas. Lists can hold any type of data, like numbers, words, or even other lists.
- Square brackets: Define the start and end of the list.
- Items: Values inside the list, separated by commas.
- Empty list: Use
[]to create a list with no items.
python
my_list = ['item1', 'item2', 'item3'] empty_list = []
Example
This example shows how to create a list with different types of items and print it.
python
my_list = [10, 'apple', 3.14, True] print(my_list)
Output
[10, 'apple', 3.14, True]
Common Pitfalls
Some common mistakes when creating lists include:
- Forgetting commas between items, which causes syntax errors.
- Using parentheses
()instead of square brackets[], which creates a tuple, not a list. - Trying to create a list without assigning it to a variable, which means you can't use it later.
python
wrong_list = (1, 2, 3) # This is a tuple, not a list correct_list = [1, 2, 3] # Missing commas example (wrong): # my_list = [1 2 3] # SyntaxError # Correct way: my_list = [1, 2, 3]
Quick Reference
Here is a quick summary to remember how to create lists:
| Action | Syntax Example |
|---|---|
| Create a list with items | [1, 2, 3] |
| Create an empty list | [] |
| List with mixed types | [1, 'two', 3.0, True] |
| Access first item | my_list[0] |
| Add item to list | my_list.append(4) |
Key Takeaways
Use square brackets [] with commas to create a list in Python.
Lists can hold different types of items together.
Remember to separate items with commas to avoid errors.
Empty lists are created with empty square brackets [].
Avoid using parentheses () when you want a list, as that creates a tuple.