Interview Q&A / Data Science

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between loc and iloc in pandas?

SHORT ANSWER

loc selects by label (index values and column names) and includes the end of a slice. iloc selects by integer position and excludes the end, like normal Python slicing.

Explain it simply

Think of a hostel. loc asks for room number 5. iloc asks for the first room in the corridor, whatever its number is. If rooms are numbered 5, 6, 7, then room 5 is also the first room, but room "1" does not exist.

Example

python
import pandas as pd
df = pd.DataFrame({"v": [10, 20, 30]}, index=[5, 6, 7])

print(df.loc[5, "v"])      # 10   (label 5)
print(df.iloc[0, 0])       # 10   (position 0, column 0)
print(df.loc[5:6].shape)   # (2, 1)  label slice includes 6
print(df.iloc[0:1].shape)  # (1, 1)  position slice excludes 1

Key differences:

  • loc slices are inclusive of the stop label; iloc slices are exclusive.
  • loc accepts boolean masks: df.loc[df["v"] > 15, "v"].
  • Setting values safely uses loc: df.loc[mask, "v"] = 0.

After filtering or sorting, the index no longer matches positions, which is where the two behave very differently.

What to say in the interview

"loc is label-based and inclusive, iloc is position-based and exclusive. I use loc with boolean masks to filter and assign, and iloc when I need the nth row. I avoid chained indexing like df[mask]["col"] = x, because it may not modify the original and triggers SettingWithCopy warnings."

Common mistakes

  • Using df.loc[0] after sorting or filtering and expecting the first row.

#pandas#indexing#python

Related questions

Practise more Data Science questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Science quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.