π Python Lists β The Ultimate Guide to Using Lists in Python | TechTown.in
In Python, if you want to store multiple items in a single variable, you donβt need arrays β you need lists. Whether itβs a list of numbers, names, or even mixed types, Python lists make it easy to organize, access, and manipulate data.
In this beginner-friendly post, weβll explore Python lists, how to create them, access them, and use common list methods with real examples.
πΉ What is a List in Python?
A list is an ordered, changeable (mutable), and indexable collection that allows duplicate values.
fruits = ["apple", "banana", "cherry"]
print(fruits)
β Output:
['apple', 'banana', 'cherry']
βοΈ How to Create a List
# List of strings
names = ["Alice", "Bob", "Charlie"]
# List of numbers
numbers = [10, 20, 30]
# Mixed data types
mixed = [1, "hello", True, 3.5]
π Access List Items by Index
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
Python uses zero-based indexing, and you can also use negative indexes.
βοΈ Slice a List
fruits = ["apple", "banana", "cherry", "mango", "grape"]
print(fruits[1:4]) # ['banana', 'cherry', 'mango']
π Change List Items
Lists are mutable β you can change items by referring to their index.
fruits[1] = "orange"
print(fruits) # ['apple', 'orange', 'cherry']
β Add Items to a List
fruits.append("kiwi") # Adds to end
fruits.insert(1, "blueberry") # Inserts at index 1
β Remove Items from a List
fruits.remove("banana") # Removes by value
fruits.pop() # Removes last item
del fruits[0] # Removes by index
π§Ή Clear All Items
fruits.clear()
print(fruits) # []
π Loop Through a List
for fruit in fruits:
print(fruit)
π List Length
print(len(fruits))
π Combine Lists
list1 = [1, 2, 3]
list2 = [4, 5]
combined = list1 + list2
Or use .extend():
list1.extend(list2)
β Check if Item Exists
if "apple" in fruits:
print("Apple is in the list.")
π Common Python List Methods
| Method | Description |
|---|---|
append() | Adds item to end |
insert() | Adds item at specified position |
remove() | Removes item by value |
pop() | Removes last item (or by index) |
clear() | Empties the list |
extend() | Adds elements from another list |
sort() | Sorts the list (ascending) |
reverse() | Reverses the order |
index() | Returns the index of a value |
count() | Counts how often a value appears |
π§ Quick Tips
- β
Use
into check if an item exists - β Lists can contain duplicate values
- β Always remember Python lists are zero-indexed
- β
Use slicing
[start:end]for sublists
π Final Thoughts
Python lists are powerful and flexible. Whether you’re creating to-do lists, processing data, or building more complex structures like stacks or queues β lists are your go-to collection type in Python.
Learn them once, use them everywhere.
π Continue learning core Python at TechTown.in