TutorialsPythonLists in Python

Lists in Python

Store and manipulate ordered collections of data — the most-used Python data structure

A list is an ordered collection of items in Python. Lists are the most common data structure you will work with as a data analyst — column names, category values, file paths, and filter conditions are all stored as lists. Lists are mutable (you can change them) and can hold any mix of data types. They are indexed starting at 0.

Syntax

my_list = [item1, item2, item3]
my_list[0]        # first item (index 0)
my_list[-1]       # last item
my_list[1:3]      # slice: items at index 1 and 2

Examples

List operations for data work
# Creating lists
regions = ["Delhi", "Noida", "Gurgaon", "Faridabad"]
salaries = [45000, 55000, 72000, 38000, 95000]

# Access by index
regions[0]       # "Delhi"
regions[-1]      # "Faridabad"  (last item)

# Slicing
salaries[1:3]    # [55000, 72000]  (index 1 and 2)
salaries[:3]     # [45000, 55000, 72000]  (first 3)
salaries[2:]     # [72000, 38000, 95000]  (from index 2)

# Modify
regions.append("Pune")       # add to end
regions.insert(1, "Mumbai")  # insert at index 1
regions.remove("Faridabad")  # remove by value
regions.pop()                # remove last item

# Useful functions
len(salaries)    # 5
sum(salaries)    # 305000
max(salaries)    # 95000
min(salaries)    # 38000
sorted(salaries) # [38000, 45000, 55000, 72000, 95000]
List comprehension — Pythonic data transformation
# Regular loop (verbose)
salaries = [45000, 55000, 72000, 38000, 95000]
above_50k = []
for s in salaries:
    if s > 50000:
        above_50k.append(s)
# [55000, 72000, 95000]

# List comprehension (Pythonic — use this)
above_50k = [s for s in salaries if s > 50000]
# [55000, 72000, 95000]

# Transform values
in_lakhs = [s / 100000 for s in salaries]
# [0.45, 0.55, 0.72, 0.38, 0.95]

# Common in pandas:
# selected_cols = [c for c in df.columns if 'sales' in c.lower()]
💡 List comprehensions are faster and more Pythonic than loops. Learn this pattern — it appears everywhere in data code.

Key Points

  • Index starts at 0: list[0] is the first item
  • Negative index: list[-1] is the last item, list[-2] is second-to-last
  • Slicing: list[start:end] — end index is exclusive
  • append() adds one item; extend() adds another list; insert() adds at a position
  • List comprehension: [expr for item in list if condition] — fast and readable

Practice Question

Given cities = ["Delhi", "Noida", "Gurgaon"], what does cities[-1] return?