Data Structures in Python: Lists, Sets and Matrices

To remove an element from a list in Python, use remove(value) to delete the first matching value, pop(index) to remove by index and return the item, or del list[index] to delete by index without returning anything. Each raises a different error on failure, so picking the right method matters for reliable code.

  • Python has four core built-in data structures: list, tuple, set and dictionary. Each has a distinct purpose and performance profile.
  • Lists are ordered and mutable, making them the go-to structure for sequences you will change over time.
  • remove(), pop() and del all delete list elements but work differently. Confusing them is one of the most common beginner bugs.
  • Sets automatically eliminate duplicates, which makes them ideal for membership testing and deduplication tasks.
  • Matrices in Python are built with nested lists for small data, or with NumPy arrays when you need speed and mathematical operations at scale.

What Is a Data Structure in Python?

A data structure is a way of organising and storing data so your program can access and modify it efficiently. Python ships with four built-in data structures: list, tuple, set and dictionary. You do not need to import anything to use them.

According to the Stack Overflow Developer Survey 2024, Python is the most used programming language among learners for the third consecutive year. Understanding its data structures is non-negotiable if you want to write real code, not just toy scripts.

Each structure solves a different problem. Lists store ordered, changeable sequences. Tuples store ordered, unchangeable sequences. Sets store unordered collections of unique items. Dictionaries store key-value pairs. Picking the right one affects both code readability and runtime performance.

According to NASSCOM’s Indian Tech Talent Report 2024, Python is the most in-demand programming language across entry-level data and software roles in India, cited by over 68% of surveyed hiring managers at Indian IT firms. That makes mastering Python data structures a direct employability skill, not an academic exercise.

If you are figuring out which technical skills to prioritise alongside Python, the guide on top skills every college student must learn before graduation is worth reading alongside this one.

Quick Comparison of Python’s Built-In Data Structures

Structure Ordered Mutable Allows Duplicates Key Use Case
List Yes Yes Yes Dynamic sequences, stacks, queues
Tuple Yes No Yes Fixed records, function return values
Set No Yes No Deduplication, membership testing
Dictionary Yes (Python 3.7+) Yes Keys: No, Values: Yes Lookups, JSON-like data, caching

How to Remove an Element from a List in Python

This is one of the most searched Python questions among students preparing for placements at companies like TCS, Infosys and Wipro. The answer sounds simple, but each method has a specific failure mode you need to know before you use it in production code. Knowing how to remove an element from a list in Python correctly separates candidates who pass technical interviews from those who do not.

Using remove() to Delete by Value

remove(value) searches the list for the first occurrence of the given value and deletes it. If the value does not exist, Python raises a ValueError. Always check membership with in before calling remove() on untrusted data.

Example: fruits = ['apple', 'banana', 'apple'] followed by fruits.remove('apple') leaves ['banana', 'apple']. Only the first match is removed. This surprises many beginners who expect all matches to disappear.

How to Remove All Occurrences of an Element from a List in Python

If you need to remove every occurrence of a value, not just the first, use a list comprehension: fruits = [x for x in fruits if x != 'apple']. This returns a new list with all matching items excluded and runs in O(n) time. It is the cleanest, most Pythonic approach for bulk value-based removal and a common question in AMCAT and CoCubes placement tests for Indian engineering graduates.

Using pop() to Delete by Index and Retrieve the Value

pop(index) removes the item at the given position and returns it. If you skip the index, it removes and returns the last element, which makes it perfect for stack operations. Calling pop() on an empty list or with an out-of-range index raises an IndexError.

Example: scores = [90, 85, 78] followed by removed = scores.pop(1) sets removed = 85 and leaves scores = [90, 78]. The return value is what makes pop() unique among the three methods.

Using del to Delete by Index or Slice

del list[index] removes an item by position without returning it. Unlike pop(), del also accepts slices, so del scores[0:2] removes the first two elements in one operation. It is the fastest option for bulk deletions but gives you nothing back.

A quick rule of thumb: use remove() when you know the value, use pop() when you need the removed value back, and use del when you know the index and do not need a return value.

remove() vs pop() vs del: Side-by-Side Reference

Method Syntax Deletes By Returns Value Error if Missing Time Complexity
remove() list.remove(value) Value (first match) No ValueError O(n)
pop() list.pop(index) Index Yes IndexError O(1) for last item, O(n) otherwise
del del list[index] or del list[i:j] Index or slice No IndexError O(n)

According to the official Python 3 documentation, remove() has O(n) time complexity because it scans the list linearly. For large lists with frequent deletions, this matters for performance.

If you are weighing your options after college, check out this overview of entry-level jobs for teens and graduates where Python skills are increasingly listed as a hiring requirement.

How to Create a Set in Python

Creating a set is straightforward: wrap comma-separated values in curly braces, or pass any iterable to the set() constructor. The key behaviour to remember is that sets discard duplicates automatically and do not preserve insertion order.

Example: unique_ids = {101, 202, 101, 303} stores only three elements, {101, 202, 303}. The duplicate 101 is silently dropped. This makes sets the fastest built-in option for deduplication tasks.

Common Set Operations You Will Actually Use

  • add(value): inserts a single element
  • remove(value): deletes an element, raises KeyError if missing
  • discard(value): deletes an element silently if it is absent, no error
  • union() or |: combines two sets
  • intersection() or &: returns only common elements
  • difference() or -: returns elements in one set but not the other

One practical example from Indian competitive coding platforms like GeeksforGeeks and LeetCode: checking whether a list of student roll numbers contains any duplicates. Convert the list to a set and compare lengths. If len(roll_list) != len(set(roll_list)), duplicates exist. This runs in O(n) time, which is significantly faster than a nested loop approach.

A JetBrains Developer Ecosystem Survey 2023 found that 84% of Python developers use lists as their most frequent data structure, while sets are used regularly by 41% of respondents. That gap shrinks as developers move from beginner to intermediate level, because sets solve problems that lists handle inefficiently.

How to Define a Matrix in Python

Python does not have a built-in matrix type. You build one using a nested list, where each inner list represents a row. For serious numerical work, the NumPy library’s ndarray is the standard choice across data science and machine learning teams.

Defining a Matrix with Nested Lists

A 3×3 matrix looks like this: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Access the element at row 1, column 2 with matrix[1][2], which returns 6. Nested lists work fine for small, static matrices in interview problems and classroom exercises.

The limitation shows up fast. Adding two nested-list matrices requires nested loops. Transposing one requires more loops. There is no built-in dot product. For anything beyond toy examples, nested lists become painful to work with.

Defining a Matrix with NumPy

NumPy, maintained by the NumFOCUS foundation, is the backbone of scientific computing in Python. According to the NumPy documentation, its arrays support vectorised operations that run in compiled C code, making them orders of magnitude faster than pure Python loops on large datasets.

Creating a NumPy matrix: import numpy as np, then mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]). Now mat.T transposes it in one call. np.dot(mat, mat) computes the matrix product. mat.shape returns (3, 3). This is why every data science course, from IIT’s online programmes to NPTEL’s Python for Data Science, teaches NumPy alongside basic Python.

If you are thinking about where Python and data skills fit in a broader career plan, the article on best career options in 2026 for students and professionals covers roles where these skills translate directly into hiring decisions. For structured learning paths, the list of top online courses for high-salary jobs includes Python-heavy programmes worth considering.

Your next practical steps this week: open a Python shell, create a list of your last five expenses as integers, remove the largest using pop() after finding its index with index(), then convert the list to a set to see how duplicates disappear. Follow that by installing NumPy with pip install numpy and building a 3×3 identity matrix using np.eye(3). Doing beats reading every time.

If you want a structured environment to build these skills with mentorship and certification, explore 3.0 University’s online certification courses in Cybersecurity, Ethical Hacking, AI, Blockchain and Web3. The programmes are designed for students, working professionals and career switchers who want practical, industry-ready skills without spending years in a classroom. You can also browse the best free online learning platforms for students if you are starting out and want to test the waters first. And if the bigger question is which direction to take your career, the guide on how to choose the right career path after graduation in 2026 is a solid starting point.

Frequently Asked Questions

What are the data structures in Python?

Python has four built-in data structures: list (ordered, mutable, allows duplicates), tuple (ordered, immutable, allows duplicates), set (unordered, mutable, no duplicates) and dictionary (key-value pairs, ordered from Python 3.7+). Beyond these, the collections module adds specialised structures like deque, Counter and OrderedDict for more specific use cases.

How do you remove an element from a list in Python?

Use list.remove(value) to delete the first matching value, list.pop(index) to delete by position and get the value back, or del list[index] to delete by position without a return value. All three modify the list in place. remove() raises ValueError if the value is absent; pop() and del raise IndexError for out-of-range indices.

How do you remove all occurrences of an element from a list in Python?

Use a list comprehension: my_list = [x for x in my_list if x != target_value]. This creates a new list excluding every instance of the target value and runs in O(n) time. It is more efficient and readable than calling remove() in a loop, which rescans the list from the start on each iteration.

What is the difference between remove, pop and del in Python?

remove(value) searches by value and deletes the first match. pop(index) deletes by index and returns the removed item, useful when you need that value later. del list[index] deletes by index or slice and returns nothing. For stack behaviour, use pop(). For value-based deletion, use remove(). For bulk slice removal, use del.

How do you create a set in Python?

Use curly braces: my_set = {1, 2, 3}. To create an empty set, use my_set = set(), not {}, which creates an empty dictionary. You can also pass any iterable: set([1, 2, 2, 3]) returns {1, 2, 3}. Sets are ideal for deduplication and fast membership checks using the in operator.

How do you define a matrix in Python?

For simple cases, use a nested list: matrix = [[1, 2], [3, 4]]. Access elements with matrix[row][col]. For numerical computing, use NumPy: import numpy as np then mat = np.array([[1, 2], [3, 4]]). NumPy supports transposition, dot products and broadcasting natively, which nested lists cannot do without manual loops.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles