Python Lists
Table of Contents
Description
A list in Python is an ordered, mutable (changeable), and heterogeneous (can store multiple data types) collection of elements. Lists are defined using square brackets [] and can contain integers, strings, other lists, etc.
Key features of Python lists:
Can grow/shrink dynamically.
Can be nested (lists inside lists).
Support indexing, slicing, and built-in methods.
Prerequisites
- Basic understanding of Python variables and data types.
- Familiarity with indexing and loops (recommended).
Examples
Here's a simple program in Python:
# Creating a list fruits = ["apple", "banana", "cherry"] # Accessing elements by index print(fruits[0]) # Output: 'apple' # Slicing a list print(fruits[1:3]) # Output: ['banana', 'cherry'] # Modifying a list fruits[1] = "orange" # Changes 'banana' to 'orange' # Adding elements fruits.append("grape") # Adds 'grape' to the end # Inserting at specific index fruits.insert(1, "kiwi") # Inserts 'kiwi' at index 1 # Removing elements fruits.remove("apple") # Removes 'apple' popped = fruits.pop() # Removes and returns last element # Length of the list print(len(fruits)) # Output: length of list # Looping through a list for fruit in fruits: print(fruit) # Nested list matrix = [[1, 2], [3, 4]] print(matrix[1][0]) # Output: 3Real-World Applications
Managing datasets (e.g., rows from a CSV).
Storing sequences of tasks, items, or logs.
Handling form data or user inputs in web apps.
Implementing stacks, queues, and buffers.
Temporary data storage during computation.
Where topic Can Be Applied
Data science: Handling arrays of data before converting to NumPy or pandas.
Web scraping: Storing text or links.
Machine learning: Storing input/output features.
Game development: Tracking score history, levels, inventory.
Automation: Looping over file names or URLs.
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What is a list in Python?
How are lists different from tuples?
What does append() vs insert() do?
Can a list contain different data types?
What is a nested list and how do you access elements in it?