Imagine you want to save the names of 50 students. Would you make 50 different variables? No, that is too much work. Python has a simple tool for this. It is called a list. A list keeps many values together in one variable. In this guide, you will learn how to make a list, get items from it, change it, and use a loop with it. If you did not read the last lesson yet, start with Python Loops: for, while, break and continue, because we will use a for loop in this post.
- What a list is and why we need it
- How to make a list and get items with an index
- How to change, add and remove items
- How to use
len()andsort() - How to loop through a list
What Is a List?
A list is a group of values saved in one variable. The values are called items. A list can keep text, numbers or both. You write a list inside square brackets [ ] and put a comma between the items.
Step 1: Make Your First List
- Open VS Code and open your python-practice folder.
- Click the New File icon and name the file
lists.py. - Type the code below.
- Press
Ctrl + Sto save the file. - Click the triangle (Play) button at the top right to run it.
fruits = ["apple", "banana", "kiwi"]
print(fruits)
print(len(fruits))
You should see this output:
['apple', 'banana', 'kiwi']
3
The list has 3 items. The function len() tells you how many items are in the list.
Step 2: Get an Item with Index
Every item in a list has a number. This number is called the index. Remember one important rule: the index starts from 0, not from 1.
fruits = ["apple", "banana", "kiwi", "mango"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
You should see this output:
apple
kiwi
mango
fruits[0]is the first item.fruits[2]is the third item.fruits[-1]is the last item. A minus index counts from the end.
Step 3: Change an Item
You can change an item by using its index:
fruits = ["apple", "banana", "kiwi"]
fruits[1] = "orange"
print(fruits)
You should see this output:
['apple', 'orange', 'kiwi']
The item at index 1 was "banana". Now it is "orange".
Step 4: Add and Remove Items
A list can grow and become smaller. Python gives you small tools for this. They are called methods.
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
fruits.insert(0, "grape")
print(fruits)
fruits.remove("banana")
print(fruits)
fruits.pop()
print(fruits)
You should see this output:
['apple', 'banana', 'mango']
['grape', 'apple', 'banana', 'mango']
['grape', 'apple', 'mango']
['grape', 'apple']
append("mango")adds an item at the end.insert(0, "grape")adds an item at the place you choose. Here it goes to index 0.remove("banana")deletes the item with that value.pop()removes the last item.
Step 5: Sort a List
The sort() method puts the items in order. Numbers go from small to big. Text goes in A to Z order.
numbers = [30, 10, 20]
numbers.sort()
print(numbers)
names = ["Sara", "Ali", "Zain"]
names.sort()
print(names)
You should see this output:
[10, 20, 30]
['Ali', 'Sara', 'Zain']
Step 6: Loop Through a List
Lists and loops work together very nicely. A for loop takes one item in every turn:
names = ["Ali", "Sara", "Zain"]
for name in names:
print("Hello", name)
You should see this output:
Hello Ali
Hello Sara
Hello Zain
In the first turn, name is "Ali". In the second turn, it is "Sara". In the third turn, it is "Zain". When the items finish, the loop stops by itself.
You can also add numbers from a list:
marks = [40, 50, 60]
total = 0
for m in marks:
total = total + m
print("Total:", total)
You should see this output:
Total: 150
Step 7: Practice Program
Let us make a small shopping list. Create a new file named shopping.py and type this:
items = []
for i in range(3):
item = input("Enter an item: ")
items.append(item)
print("Your shopping list:")
for item in items:
print("-", item)
If you type milk, eggs and bread, you will see this output:
Enter an item: milk
Enter an item: eggs
Enter an item: bread
Your shopping list:
- milk
- eggs
- bread
Here we started with an empty list []. Then we used a loop, input() and append() to fill it. At the end, a second loop printed all the items.
Common Errors and How to Fix Them
Error 1: IndexError: list index out of range
You asked for an index that does not exist:
fruits = ["apple", "banana"]
print(fruits[2])
This list has only index 0 and index 1. Use a smaller index:
print(fruits[1])
Error 2: ValueError: list.remove(x): x not in list
You tried to remove a value that is not in the list. Check the spelling and the capital letters. "Apple" and "apple" are not the same.
Error 3: TypeError: list indices must be integers
You used text as an index, like fruits["0"]. An index must be a whole number. Write fruits[0].
Error 4: NameError: name 'apple' is not defined
You forgot the quotes around the text. Write ["apple", "banana"], not [apple, banana].
Common Mistakes Beginners Make
- Starting the index from 1. The first item is always index 0.
- Using the wrong brackets. A list uses square brackets
[ ], not round brackets. - Forgetting the quotes. Text items need quotes, but numbers do not.
- Printing the result of sort().
sort()changes the list itself. Writenumbers.sort()first, thenprint(numbers). - Using an index that is too big. The last index is always
len(list) - 1. - Forgetting the colon or the 4 spaces in a
forloop.
Practice Time
Try these small tasks on your own. Click a question to open the code box, write your Python code and press Run. If your code is correct, you will see a green message. If there is an error, you will see the error, the line number and a tip to fix it.
- Print the first item of a list.
- Add an item to a list.
- Print every name in a list.
- Find the total of a list of marks.
What to Learn Next
Now you can keep many values in one variable and loop through them. The next step is dictionaries. A dictionary keeps data in pairs, like a name and its phone number. In the next post, we will learn dictionaries with simple examples. If you missed the full learning plan, read my Python roadmap for beginners.
Frequently Asked Questions (FAQs)
What is a list in Python?
A list is a group of values saved in one variable. You write it inside square brackets, like ["apple", "banana"]. It can keep text, numbers or both.
Why does the index start from 0?
This is how Python and many other languages count. The first item is at index 0, the second item is at index 1, and so on. It feels strange at first, but you will get used to it with practice.
What is the difference between append() and insert()?
append() always adds the new item at the end of the list. insert() lets you choose the place, like insert(0, "grape") to add it at the start.
Can a list keep different types of values?
Yes. A list like ["Ali", 20, True] is fine. But in most programs, it is cleaner to keep the same type of values in one list.
Final Thoughts
Lists are used in almost every Python program. Remember the three big ideas: the index starts from 0, methods like append() and remove() change the list, and a for loop can visit every item. Practice a little every day, and try to change the items in the examples to see what happens.




Comments
Post a Comment