loc vs iloc
If you are learning Python, Data Science, Machine Learning, or Pandas, one question will confuse you again and again:
What is the real difference between
locandiloc?
After reading this blog post, you will never be confused again.
Everything is explained using simple language, clear examples, interview tips, and easy memory tricks.
📌 Why Is loc vs iloc So Important?
- Data selection is a core concept in Pandas
- This question is very common in interviews
- Wrong slicing can give wrong results
- 90% of beginners make mistakes here
If you want to become a Data Analyst, Data Scientist, or Python Developer, this topic is mandatory.
🔹 loc vs iloc – Main Difference (Quick Table)
| Feature | loc | iloc |
|---|---|---|
| Access type | Label-based | Index-based (position) |
| Used for | Row/Column names | Row/Column numbers |
| Index start | Depends on labels | Always starts from 0 |
| Slice end | Inclusive | Exclusive |
| Boolean filtering | ✅ Allowed | ❌ Not directly |
👉 One-line Summary
- loc → works with names
- iloc → works with numbers
🔹 Example DataFrame
import pandas as pd
data = {
'Name': ['Amit', 'Ravi', 'Sita', 'Neha'],
'Age': [25, 30, 28, 22],
'City': ['Delhi', 'Mumbai', 'Pune', 'Chennai']
}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd'])
print(df)
📊 Output
| Index | Name | Age | City |
|---|---|---|---|
| a | Amit | 25 | Delhi |
| b | Ravi | 30 | Mumbai |
| c | Sita | 28 | Pune |
| d | Neha | 22 | Chennai |
🔹 Using loc (Label-Based Selection)
✅ 1. Select a Single Row
df.loc['b']
👉 Returns the row with index ‘b’
✅ 2. Select Multiple Rows
df.loc[['a', 'c']]
👉 Returns rows ‘a’ and ‘c’
✅ 3. Select a Range of Rows (Inclusive)
df.loc['a':'c']
👉 Includes ‘a’ to ‘c’, and ‘c’ is included
✅ 4. Select Specific Columns
df.loc[:, ['Name', 'City']]
👉 All rows with only Name and City
✅ 5. Boolean Filtering (Very Powerful)
df.loc[df['Age'] > 25]
👉 Rows where Age > 25
📌 Interview Tip: Boolean filtering is easiest with loc
🔹 Using iloc (Index-Based Selection)
✅ 1. Select Row by Position
df.iloc[1]
👉 Returns the second row (index starts from 0)
✅ 2. Select Multiple Rows by Position
df.iloc[[0, 2]]
👉 Returns the first and third rows
✅ 3. Select Row Range (Exclusive End)
df.iloc[0:3]
👉 Returns rows 0, 1, 2 (3 is NOT included)
✅ 4. Select Rows and Columns Together
df.iloc[:, 0:2]
👉 All rows with the first two columns
🔥 MOST IMPORTANT Difference (Exam Favorite)
df.loc['a':'c'] # includes 'c'
df.iloc[0:3] # excludes index 3
📌 Remember:
- loc → end is included
- iloc → end is excluded
🧠 Easy Memory Trick (Never Forget)
- loc = L → Label
- iloc = I → Index (number)
That’s it. Confusion gone 💡
🔹 When Should You Use What?
✅ Use loc when:
- Your DataFrame has custom labels
- You want to select using column names
- You need boolean filtering
✅ Use iloc when:
- You want position-based slicing
- You are working inside loops
- You know the exact index number
