Python Lists Explained for Beginners (With Simple Examples)
Python Lists Explained for Beginners (With Simple Examples)
Introduction
In the previous post, we learned about Python functions. Now it’s time to learn one of the most important data structures in Python — Lists.
Lists allow us to store multiple values in a single variable.
---What is a List?
A list is a collection of items stored in a single variable.
Creating a List
numbers = [1, 2, 3, 4, 5]
names = ["Ayush", "Rahul", "Aman"]
Accessing List Items
Each item in a list has an index starting from 0.
names = ["Ayush", "Rahul", "Aman"]
print(names[0])
print(names[1])
Negative Indexing
Negative indexing starts from the end of the list.
names = ["Ayush", "Rahul", "Aman"]
print(names[-1])
Changing List Items
Lists are mutable, meaning their values can be changed.
numbers = [1, 2, 3]
numbers[1] = 10
print(numbers)
Adding Items to a List
Using append()
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
Using insert()
numbers.insert(1, 99)
print(numbers)
Removing Items from a List
numbers = [1, 2, 3, 4]
numbers.remove(3)
print(numbers)
numbers.pop()
print(numbers)
Looping Through a List
We can use loops to access each item in a list.
names = ["Ayush", "Rahul", "Aman"]
for name in names:
print(name)
List Length
Use the len() function to find the number of items in a list.
numbers = [1, 2, 3, 4]
print(len(numbers))
Common Beginner Mistakes
- Using wrong index number
- Forgetting square brackets
- Confusing append() and insert()
What You Learned in This Post
- What lists are
- How to create and access lists
- Add and remove items
- Loop through lists
What’s Next?
Now that you understand lists, the next step is learning about tuples and sets.
Next Post: Python Tuples Explained for Beginners
---👋 About the Author
Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast
📧 Email:
aygupta9898@gmail.com
Comments
Post a Comment