TutorialsPythonPython Lists

Python Lists

Store, access and manipulate collections of data with Python lists

Lists are the most common Python data structure. A list is an ordered collection of items — numbers, strings, or a mix. In data analysis, you use lists to store column names, filter values, file paths, category labels, and more. Lists are mutable (you can change them) and allow duplicates. They are indexed starting at 0. Understanding lists is the foundation for understanding how Pandas DataFrames work under the hood.

Examples

List operations
# Create
regions = ["Delhi", "Noida", "Gurgaon", "Faridabad"]
scores = [85, 92, 78, 95, 88]

# Access
regions[0]      # "Delhi"   (first)
regions[-1]     # "Faridabad" (last)
regions[1:3]    # ["Noida", "Gurgaon"] (slice)

# Modify
regions.append("Ghaziabad")         # add to end
regions.insert(1, "Greater Noida")  # insert at index 1
regions.remove("Faridabad")         # remove by value
popped = regions.pop()              # remove and return last

# Info
len(regions)        # number of items
"Delhi" in regions  # True/False
regions.count("Delhi")  # how many times it appears

# Sorting
scores.sort()               # in-place sort (ascending)
scores.sort(reverse=True)   # descending
sorted_copy = sorted(scores) # new sorted list, original unchanged
💡 sort() modifies the list in place. sorted() returns a new list and leaves the original untouched.
List comprehensions — powerful one-liners
sales = [45000, 18000, 62000, 9000, 51000]

# Filter: only sales above 20000
high_sales = [s for s in sales if s > 20000]
# [45000, 62000, 51000]

# Transform: convert to lakhs
in_lakhs = [s / 100000 for s in sales]
# [0.45, 0.18, 0.62, 0.09, 0.51]

# Both: filter AND transform
high_in_lakhs = [s/100000 for s in sales if s > 20000]
# [0.45, 0.62, 0.51]

# Practical: get column names that contain "Sales"
columns = ["Date", "Sales_Q1", "Cost_Q1", "Sales_Q2", "Units"]
sales_cols = [c for c in columns if "Sales" in c]
# ["Sales_Q1", "Sales_Q2"]
💡 List comprehensions replace 4-line for loops with 1 line. Pandas uses this logic internally.

Key Points

  • Index starts at 0: list[0] is the first item, list[-1] is the last
  • Slicing list[start:end] — end is exclusive: list[1:3] gives items at index 1 and 2
  • append() adds one item; extend() adds all items from another list
  • List comprehensions are faster than for loops for simple transformations
  • In Pandas, df.columns.tolist() returns column names as a Python list

Practice Question

What does scores[-1] return if scores = [85, 92, 78, 95]?

Related Topics

Tuples and SetsUse tuples for fixed data and sets for unique value operationsDictionaries in PythonKey-value pairs for fast lookups, mappings and structured dataLoops — for and whileIterate over data, automate repetitive tasks, and process multiple files with loopsNumPy ArraysFast numerical computation with NumPy arrays — the engine behind Pandas