CS Pathfinder Logo CS Pathfinder

Unit 2 · Lists in Python

Introduction to Lists in Python

Learn the fundamentals of Python's most versatile data structure: creating lists, understanding their characteristics, and using built-in functions for university and competitive exams.

Introduction to Lists

A List in Python is one of the most powerful and widely used built-in data structures. It is an ordered and mutable collection of items, which allows you to group multiple values under a single variable name. Think of a list as a dynamic, super-powered array that can hold items of any data type.

Easy Definition

A list is a flexible container where you can store a sequence of items. You can access them by their position, and you can change, add, or remove items at any time.

Real-Life Analogy

  • A shopping list where you can add or remove items.
  • A list of students in a class, arranged in a specific order.
  • A playlist of songs where you can reorder, add, or delete songs.

Examination Point of View

  • Definition and characteristics of a list (ordered, mutable, allows duplicates).
  • Difference between a list and a string (mutability vs. immutability).
  • Difference between a Python list and an array in languages like C/Java.
  • Syntax for creating and modifying lists.
  • Predicting the output of built-in functions like len(), max(), min(), and sum().
Lists in Python
Figure 2.15 — Visual representation of a Python list containing mixed data types.

Table of Contents

Characteristics of a List

Understanding the core properties of lists is crucial for exams and interviews. These features define how lists behave and when to use them.

Feature Description & Importance Example
Ordered Elements maintain a specific sequence. This means the position of each item is fixed and can be accessed by an index. This is vital for tasks where sequence matters, like steps in a recipe. [1, 2, 3] is different from [3, 2, 1].
Mutable You can change, add, or remove elements after the list is created. This flexibility is the primary advantage of lists over immutable types like tuples and strings. my_list[0] = 100 is a valid operation.
Allows Duplicates A list can contain multiple instances of the same element. This is useful for storing data like poll results or scores where values can repeat. [10, 20, 10, 30] is a valid list.
Dynamic Lists can grow and shrink in size as needed. You don't need to declare a fixed size beforehand, unlike arrays in C/Java. Methods like append() and pop() change the list's size.
Heterogeneous A single list can store items of different data types (integers, strings, booleans, other lists, etc.). This makes them extremely versatile. ["text", 100, True] is a valid list.

Creating Lists

Lists are created by placing comma-separated values inside square brackets [].

# A list of integers
numbers = [10, 20, 30, 40]

# A list of strings
names = ["Alice", "Bob", "Charlie"]

# An empty list
empty_list = []

print(names)

You can also create a list from any other iterable (like a string, tuple, or range) using the list() constructor. This is a common technique in competitive programming and data processing.

# Create a list of characters from a string
list_from_string = list("Python")
print(list_from_string)  # Output: ['P', 'y', 't', 'h', 'o', 'n']

# Create a list from a tuple
list_from_tuple = list((1, 2, 3))
print(list_from_tuple)   # Output: [1, 2, 3]

List vs. Tuple vs. Array (A Key Comparison)

This comparison is a favorite in university vivas and technical interviews.

Feature Python List Python Tuple Array (in C/Java)
Mutability Mutable (Changeable) Immutable (Not Changeable) Mutable
Size Dynamic (can grow/shrink) Fixed Fixed (declared at creation)
Data Types Heterogeneous (mixed types) Heterogeneous (mixed types) Homogeneous (same type only)
Syntax [1, "a"] (1, "a") int arr[5];
Performance Slightly slower due to flexibility Faster than lists (less overhead) Very fast, memory-efficient

List Mutability (A Crucial Concept)

Unlike strings and tuples, lists are mutable. This means you can change their content directly without creating a new object. This is a critical concept and a frequent topic in exams.

# Lists are MUTABLE
fruits = ["apple", "banana", "cherry"]
print(f"Original list: {fruits}")
print(f"Memory ID before change: {id(fruits)}")

fruits[1] = "mango"  # Replaces "banana" with "mango" in the same list object

print(f"Modified list: {fruits}")
print(f"Memory ID after change:  {id(fruits)}") # The ID remains the same!

Contrast with Strings (Immutable)

Trying to modify a character in a string by its index will raise a TypeError. You must create a new string, which gets a new memory ID.

my_string = "Hello"
print(f"Original string ID: {id(my_string)}")
# my_string[0] = "J"  # This will cause a TypeError!

# The correct way is to create a new string
new_string = "J" + my_string[1:]
print(f"New string: {new_string}")
print(f"New string ID:      {id(new_string)}") # The ID is different!

Common Built-In Functions for Lists

Python provides several built-in functions that work with lists to quickly get information.

scores = [80, 95, 70, 90]
print(len(scores))  # 4 (Returns the number of elements)
print(max(scores))  # 95 (Returns the largest value)
print(min(scores))  # 70 (Returns the smallest value)
print(sum(scores))  # 335 (Adds all numeric elements)

Exam Trap: `sorted()` function vs. `sort()` method

This is one of the most common confusion points for students.

  • sorted(my_list): A built-in function that takes a list (or any iterable) and returns a new, sorted list. The original list is left unmodified.
  • my_list.sort(): A method of the list object. It sorts the list in-place (modifies the original list) and returns None.
# Using sorted() function
original_list = [3, 1, 2]
new_sorted_list = sorted(original_list)
print(f"Original list: {original_list}") # Output: Original list: [3, 1, 2]
print(f"New sorted list: {new_sorted_list}") # Output: New sorted list: [1, 2, 3]

# Using sort() method
another_list = [3, 1, 2]
result_of_sort = another_list.sort()
print(f"Modified list: {another_list}") # Output: Modified list: [1, 2, 3]
print(f"Result of sort(): {result_of_sort}") # Output: Result of sort(): None

Exam Corner: Key Questions & Concepts

Focus on these areas to ace your university exams and technical interviews.

Key Concepts for Theory/MCQs

  • Define a list and its primary characteristics (ordered, mutable, allows duplicates, dynamic, heterogeneous).
  • What is the difference between a list and a tuple? (Mutability, syntax, use cases).
  • What is the difference between a Python list and an array in C/Java? (Dynamic size, heterogeneous types).
  • Explain mutability in Python lists. Provide an example.
  • What does sorted() do? What does list.sort() do? (Return value and side effects).

Code Output Prediction

  • Predict the output of operations involving list creation, indexing, slicing, and modification.
  • Predict the output of using `len()`, `max()`, `min()`, `sum()` on lists.
  • Predict the output when `sorted()` and `list.sort()` are used.
  • Trace the effect of list operations on memory IDs to demonstrate mutability.

Interview Questions

  • When would you choose a list over a tuple?
  • How can you efficiently check for the existence of an item in a list? (Hint: `in` operator).
  • Explain the performance implications of frequent list modifications (e.g., inserting at the beginning).
  • What are common pitfalls when working with lists? (e.g., `sort()` returning `None`, shallow vs. deep copies - *advanced*).

Competitive Exam Notes

  • Lists are crucial for implementing stacks and queues, common data structures in algorithms.
  • Understanding list comprehensions (though covered later) can lead to very concise and efficient code for list creation and transformation.
  • Be mindful of time complexity when performing operations on large lists, especially insertions/deletions at the beginning.

Summary

Python lists are dynamic, ordered, mutable, and heterogeneous collections. Their flexibility allows them to store various data types and be modified in-place. Understanding their characteristics, creation methods, and the behavior of built-in functions like sorted() versus the sort() method is essential for academic success and technical interviews. Always pay close attention to the distinction between functions that return new objects and methods that modify objects in-place.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.