Bird
Raised Fist0
Pandasdata~20 mins

loc vs iloc mental model in Pandas - Practice Questions

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Loc vs Iloc Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of loc with label slicing
What is the output of this code snippet using loc with label slicing on a DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [10, 20, 30, 40],
    'B': [1, 2, 3, 4]
}, index=['a', 'b', 'c', 'd'])

result = df.loc['b':'d', 'A']
print(result)
A
b    20
c    30
d    40
Name: A, dtype: int64
B
b    20
c    30
Name: A, dtype: int64
C
1    20
2    30
3    40
Name: A, dtype: int64
D
20    1
30    2
40    3
Name: A, dtype: int64
Attempts:
2 left
💡 Hint
Remember that loc includes the end label in slicing.
❓ Predict Output
intermediate
2:00remaining
Output of iloc with integer slicing
What is the output of this code snippet using iloc with integer slicing on a DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [10, 20, 30, 40],
    'B': [1, 2, 3, 4]
}, index=['a', 'b', 'c', 'd'])

result = df.iloc[1:3, 0]
print(result)
A
b    20
c    30
Name: A, dtype: int64
B
b    20
c    30
d    40
Name: A, dtype: int64
C
1    20
2    30
Name: A, dtype: int64
D
20    1
30    2
Name: A, dtype: int64
Attempts:
2 left
💡 Hint
Remember that iloc uses integer positions and excludes the end index in slicing.
❓ data_output
advanced
2:30remaining
Difference in output between loc and iloc with mixed index
Given this DataFrame with a non-integer index, what is the output of df.loc[2:4, 'X'] and df.iloc[2:4, 0]?
Pandas
import pandas as pd

df = pd.DataFrame({
    'X': [100, 200, 300, 400, 500],
    'Y': [5, 4, 3, 2, 1]
}, index=[1, 2, 3, 4, 5])

loc_result = df.loc[2:4, 'X']
iloc_result = df.iloc[2:4, 0]
print('loc_result:\n', loc_result)
print('iloc_result:\n', iloc_result)
A
loc_result:
1    100
2    200
3    300
Name: X, dtype: int64
iloc_result:
2    200
3    300
Name: X, dtype: int64
B
loc_result:
2    200
3    300
4    400
Name: X, dtype: int64
iloc_result:
2    200
3    300
Name: X, dtype: int64
C
loc_result:
2    200
3    300
4    400
Name: X, dtype: int64
iloc_result:
3    300
4    400
Name: X, dtype: int64
D
loc_result:
3    300
4    400
5    500
Name: X, dtype: int64
iloc_result:
1    100
2    200
Name: X, dtype: int64
Attempts:
2 left
💡 Hint
Recall that loc uses labels and includes the end label, while iloc uses integer positions and excludes the end index.
🔧 Debug
advanced
2:00remaining
Identify the error in using loc with integer index
What error will this code raise and why?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
}, index=[10, 20, 30])

result = df.loc[1]
print(result)
ATypeError: unhashable type: 'int'
BIndexError: single positional indexer is out-of-bounds
CKeyError: 1
DNo error, prints the first row
Attempts:
2 left
💡 Hint
Check if the label 1 exists in the DataFrame index.
🚀 Application
expert
2:30remaining
Selecting rows with loc vs iloc in a real-world scenario
You have a DataFrame df with a date index from '2023-01-01' to '2023-01-10'. You want to select data from '2023-01-03' to '2023-01-06'. Which option correctly selects these rows?
Pandas
import pandas as pd

dates = pd.date_range('2023-01-01', '2023-01-10')
df = pd.DataFrame({'value': range(10)}, index=dates)

# Select rows here
Adf.iloc[2:6]
Bdf.iloc['2023-01-03':'2023-01-06']
Cdf.loc[2:5]
Ddf.loc['2023-01-03':'2023-01-06']
Attempts:
2 left
💡 Hint
Remember that loc uses labels (dates here), and iloc uses integer positions.

Practice

(1/5)
1. What is the main difference between loc and iloc in pandas?
easy
A. loc uses labels, iloc uses integer positions
B. loc uses integer positions, iloc uses labels
C. loc selects columns only, iloc selects rows only
D. loc is faster than iloc

Solution

  1. Step 1: Understand loc selection method

    loc selects data by row and column labels, meaning it uses the actual names of rows and columns.
  2. Step 2: Understand iloc selection method

    iloc selects data by integer positions, starting from 0, ignoring labels.
  3. Final Answer:

    loc uses labels, iloc uses integer positions -> Option A
  4. Quick Check:

    loc = labels, iloc = positions [OK]
Hint: Remember: loc = labels, iloc = integer positions [OK]
Common Mistakes:
  • Confusing labels with positions
  • Thinking loc uses positions
  • Assuming iloc uses labels
2. Which of the following is the correct syntax to select rows with labels 'a' to 'c' and columns 'x' to 'z' using loc?
easy
A. df.loc['a':'c', 'x':'z']
B. df.iloc['a':'c', 'x':'z']
C. df.loc[0:2, 0:2]
D. df.iloc[0:2, 'x':'z']

Solution

  1. Step 1: Identify loc syntax

    loc uses labels, so slicing with labels like 'a':'c' and 'x':'z' is valid.
  2. Step 2: Check other options

    Selections using iloc with label slices are invalid because iloc requires integer positions. Using integer slices with loc is incorrect when the labels are strings like 'a', 'c', etc.
  3. Final Answer:

    df.loc['a':'c', 'x':'z'] -> Option A
  4. Quick Check:

    loc uses labels in slices [OK]
Hint: Use labels inside loc brackets, positions inside iloc [OK]
Common Mistakes:
  • Using integer positions with loc
  • Using labels with iloc
  • Mixing loc and iloc syntax
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'A':[10,20,30], 'B':[40,50,60]}, index=['x','y','z'])

What is the output of df.iloc[1, 0]?
medium
A. 30
B. 40
C. 50
D. 20

Solution

  1. Step 1: Understand DataFrame structure

    Rows are labeled 'x','y','z' with values in column 'A' as [10,20,30]. Positions start at 0, so row 1 is 'y', column 0 is 'A'.
  2. Step 2: Apply iloc selection

    df.iloc[1, 0] selects row at position 1 ('y') and column at position 0 ('A'), value is 20.
  3. Final Answer:

    20 -> Option D
  4. Quick Check:

    iloc uses positions: row 1, col 0 = 20 [OK]
Hint: iloc uses zero-based positions, count rows and columns from 0 [OK]
Common Mistakes:
  • Using labels instead of positions
  • Confusing row and column indices
  • Selecting wrong cell by mixing loc and iloc
4. Consider this code:
import pandas as pd
df = pd.DataFrame({'A':[1,2,3]}, index=[10,20,30])
print(df.loc[1])

What error will occur and why?
medium
A. No error, prints 2
B. KeyError because label 1 does not exist in index
C. IndexError because position 1 is out of range
D. TypeError because loc expects string labels

Solution

  1. Step 1: Check DataFrame index labels

    Index labels are [10, 20, 30], so label 1 is not present.
  2. Step 2: Understand loc behavior

    loc looks for label 1, which does not exist, causing a KeyError.
  3. Final Answer:

    KeyError because label 1 does not exist in index -> Option B
  4. Quick Check:

    loc needs existing labels, else KeyError [OK]
Hint: loc needs exact labels; missing label causes KeyError [OK]
Common Mistakes:
  • Thinking loc uses positions
  • Expecting no error when label missing
  • Confusing KeyError with IndexError
5. You have a DataFrame with non-numeric row labels:
import pandas as pd
df = pd.DataFrame({'Score':[88, 92, 95]}, index=['John', 'Jane', 'Doe'])

You want to select the second row using loc and iloc. Which code will correctly select the second row and what will be the difference in output?
hard
A. df.loc['Jane'] and df.iloc['Jane'] both select by label 'Jane'; output differs
B. df.loc[1] selects by position 1; df.iloc['Jane'] selects by label 'Jane'; both return the same row
C. df.loc['Jane'] selects by label 'Jane'; df.iloc[1] selects by position 1; both return the same row
D. df.loc[1] and df.iloc[1] both select by position 1; output differs

Solution

  1. Step 1: Understand row labels and positions

    Rows are labeled 'John', 'Jane', 'Doe' at positions 0, 1, 2 respectively.
  2. Step 2: Use loc and iloc correctly

    df.loc['Jane'] selects row with label 'Jane'. df.iloc[1] selects row at position 1, which is also 'Jane'. Both return the same row.
  3. Final Answer:

    df.loc['Jane'] selects by label 'Jane'; df.iloc[1] selects by position 1; both return the same row -> Option C
  4. Quick Check:

    loc uses label, iloc uses position; same row here [OK]
Hint: loc needs label, iloc needs position; same row if label matches position [OK]
Common Mistakes:
  • Using integer with loc
  • Using label with iloc
  • Assuming loc and iloc always differ
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard