Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python List vs Dictionary: What's the Difference?

Python List vs Dictionary - Complete Comparison

Learn the key differences between Python lists and dictionaries and when to use each.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Lists vs Dictionaries – What's the Big Difference?
  • Access: Index vs Key
  • Performance: Which Is Faster?
  • Memory Usage
  • Structure: Ordered vs Key-Value
  • Mutability: Both Can Change
  • When to Use Each
  • Quick Summary Table
  • Common Mistakes
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Access method — index vs key-based access
  • Performance — which one is faster for what
  • Memory usage — which one uses less memory
  • Structure — ordered sequence vs key-value pairs
  • Mutability — both can change
  • When to use — choosing the right one

Lists vs Dictionaries – What's the Big Difference?

Lists and dictionaries are two of the most commonly used data structures in Python. They look different, they work differently, and they're built for different purposes.

The short answer is: lists are ordered sequences accessed by index, dictionaries are key-value pairs accessed by key. But there's a lot more to it than that. Let's break it down.

💡 Here's the thing: The choice between a list and a dictionary affects performance, memory, and how you write your code. Choose wisely!

Access: Index vs Key

1

Lists Use Index, Dictionaries Use Keys

This is the most important difference. Lists use numeric indices (0, 1, 2...). Dictionaries use keys (strings, numbers, tuples).

# List — access by index
my_list = ["apple", "banana", "cherry"]
print(my_list[0])  # apple
print(my_list[1])  # banana
print(my_list[2])  # cherry

# Dictionary — access by key
my_dict = {"name": "Alice", "age": 25, "city": "NYC"}
print(my_dict["name"])  # Alice
print(my_dict["age"])   # 25
print(my_dict["city"])  # NYC

# Keys are meaningful!
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(f"{person['name']} is {person['age']} years old")

# Compare:
person_list = ["Alice", 25, "NYC"]
print(f"{person_list[0]} is {person_list[1]} years old")  # Less readable

What this means for you:

  • Lists — use indices (0, 1, 2...)
  • Dictionaries — use keys (strings, numbers, tuples)
  • Dictionaries are more readable for labeled data

Quick Check: How do you access a value in a dictionary? (Answer: Using a key)

Performance: Which Is Faster?

2

Dictionaries Are Faster for Lookups

Dictionaries use hash tables, which allow O(1) lookup time. Lists require O(n) time to find an element by value.

import time

# Create data
big_list = list(range(1000000))
big_dict = {i: i for i in range(1000000)}

# Lookup by index (list — fast)
start = time.time()
big_list[999999]
list_index_time = time.time() - start

# Lookup by key (dict — fast)
start = time.time()
big_dict[999999]
dict_key_time = time.time() - start

print(f"List index lookup: {list_index_time:.6f}s")  # Very fast
print(f"Dict key lookup: {dict_key_time:.6f}s")      # Very fast

# Membership test (list — slow)
start = time.time()
999999 in big_list
list_membership_time = time.time() - start

# Membership test (dict — fast)
start = time.time()
999999 in big_dict
dict_membership_time = time.time() - start

print(f"List membership: {list_membership_time:.6f}s")  # Slow
print(f"Dict membership: {dict_membership_time:.6f}s")  # Fast

Performance summary:

  • Lists — fast for index access, slow for value lookup
  • Dictionaries — fast for key lookup, fast for membership
  • Choose based on what you need

Quick Check: Which is faster for checking if an item exists? (Answer: Dictionary)

Memory Usage

3

Lists Use Less Memory

Lists are more memory-efficient than dictionaries because they don't store keys or hash tables. Dictionaries have overhead for storing keys and hash values.

import sys

# Create list and dictionary with same data
my_list = list(range(1000))
my_dict = {i: i for i in range(1000)}

print(f"List size: {sys.getsizeof(my_list)} bytes")
print(f"Dict size: {sys.getsizeof(my_dict)} bytes")

# Output example:
# List size: 8,056 bytes
# Dict size: 36,960 bytes

# Dictionaries use much more memory!
# Why? They store keys, values, and hash tables.

Memory summary:

  • Lists — use less memory
  • Dictionaries — use more memory (store keys + hash tables)
  • For large datasets, memory matters

Quick Check: Which uses less memory: list or dictionary? (Answer: List)

Structure: Ordered vs Key-Value

4

Lists Are Ordered Sequences, Dictionaries Are Key-Value Pairs

Lists store items in a specific order. Dictionaries store key-value pairs (order is preserved in Python 3.7+).

# List — ordered sequence
my_list = [1, 2, 3, 4, 5]
print(my_list[0])  # 1 — position matters

# Dictionary — key-value pairs
my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict["a"])  # 1 — key matters

# Lists are good for:
# - Sequences (steps, order matters)
# - Stacks and queues
# - Data where position matters

# Dictionaries are good for:
# - Mapping (name → value)
# - Lookup tables
# - Data where meaning matters

Key difference:

  • Lists — position matters
  • Dictionaries — meaning (key) matters
  • Choose based on what you need

Mutability: Both Can Change

5

Both Lists and Dictionaries Are Mutable

Both lists and dictionaries can be changed after creation. You can add, remove, or modify elements.

# List — mutable
my_list = [1, 2, 3]
my_list[0] = 10    # Change
my_list.append(4)  # Add
my_list.remove(2)  # Remove
print(my_list)     # [10, 3, 4]

# Dictionary — mutable
my_dict = {"a": 1, "b": 2, "c": 3}
my_dict["a"] = 10  # Change
my_dict["d"] = 4   # Add
del my_dict["b"]   # Remove
print(my_dict)     # {'a': 10, 'c': 3, 'd': 4}

# Both can change, but they change differently:
# Lists change by position
# Dictionaries change by key

Key point:

  • Both lists and dictionaries are mutable
  • Lists maintain order when modified
  • Dictionaries maintain key-value structure

When to Use Each

6

Which One Should You Choose?

# Use lists when:
# 1. Order matters
playlist = ["song1", "song2", "song3"]

# 2. You need to access by position
first_song = playlist[0]

# 3. You have a simple sequence
scores = [85, 92, 78, 90]

# 4. You need to sort or reverse
scores.sort()

# Use dictionaries when:
# 1. You have labeled data
user = {"name": "Alice", "age": 25, "city": "NYC"}

# 2. You need to look up by a meaningful key
print(user["name"])  # Alice

# 3. You have key-value pairs
phone_book = {"Alice": "555-1234", "Bob": "555-5678"}

# 4. You need fast lookups
if "Alice" in phone_book:
    print(phone_book["Alice"])

Simple rule of thumb:

  • Use lists — when order or position matters
  • Use dictionaries — when you have key-value data
  • When in doubt, ask: "Do I need a key or an index?"

Quick Summary Table

7
Feature List Dictionary
Access By index (position) By key (meaning)
Lookup Speed O(n) — slow O(1) — fast ✅
Memory Smaller ✅ Larger
Order Preserved ✅ Preserved (Python 3.7+) ✅
Mutability Mutable ✅ Mutable ✅
Keys No keys (indices only) Yes, meaningful keys ✅
Best For Ordered sequences Key-value data, lookups

Common Mistakes

8

Things to Watch Out For

Using a Dictionary When You Need Order

# WRONG — dictionaries are key-value, not ordered sequences
my_dict = {"first": 1, "second": 2, "third": 3}
# You can't access by position reliably

# CORRECT — use a list for ordered data
my_list = [1, 2, 3]
print(my_list[0])  # 1

Using a List for Lookups

# WRONG — list membership is slow for large data
my_list = list(range(1000000))
# if 999999 in my_list:  # Slow!

# CORRECT — use a dictionary for fast lookups
my_dict = {i: i for i in range(1000000)}
if 999999 in my_dict:  # Fast!

Assuming Dictionary Keys Are Always Strings

# WRONG — keys can be any immutable type
my_dict = {1: "one", "two": 2, (1, 2): "tuple"}

# CORRECT — know that keys must be hashable
my_dict = {1: "one", "two": 2, (1, 2): "tuple"}  # All valid

Quick Check: What's the most common mistake with dictionaries? (Answer: Using them when a list would be simpler)

Try It Yourself

Compare lists and dictionaries in the editor below. Change the code and see what happens.

Loading Pyodide... 0%
Python Code Editor
========================================
LIST VS DICTIONARY COMPARISON
========================================

List: ['Alice', 25, 'NYC']
Dictionary: {'name': 'Alice', 'age': 25, 'city': 'NYC'}

1. ACCESS
List[0]: Alice
Dict['name']: Alice

2. PERFORMANCE (MEMBERSHIP)
List membership: 0.008000s (slow)
Dict membership: 0.000001s (fast)

3. MEMORY USAGE
List size: 88 bytes
Dict size: 184 bytes

4. WHEN TO USE
Use LIST when: order matters, simple sequence, need indexing
Use DICT when: key-value data, fast lookups, meaningful keys

List vs Dictionary comparison complete!
🏆

You've Got It!

You now understand the key differences between lists and dictionaries — access method, performance, memory, structure, and when to use each. This is a common interview question, so you're ready!

Quick Quiz

Test what you've learned:

1. How do you access a value in a dictionary?
2. Which is faster for membership testing (checking if something exists)?
3. Which uses less memory?
4. When should you use a dictionary instead of a list?
5. Can dictionary keys be any type?

Frequently Asked Questions

Which is faster: list or dictionary? ▼

For membership testing and key lookups, dictionaries are much faster (O(1) vs O(n)). For index access and iteration, lists are faster.

Can I convert a list to a dictionary? ▼

Yes, if you have pairs of data. Use dict(zip(keys, values)) or dictionary comprehension.

Do dictionaries preserve order? ▼

Yes, starting from Python 3.7, dictionaries preserve insertion order. In Python 3.6, it was an implementation detail.

What types can be dictionary keys? ▼

Any immutable type: strings, numbers, tuples, frozensets. Lists and dictionaries cannot be keys because they are mutable.

Which uses less memory: list or dictionary? ▼

Lists use less memory because dictionaries store keys and hash tables. For large datasets, the difference can be significant.

What's a common interview question about lists and dictionaries? ▼

The most common is: "What's the difference between a list and a dictionary?" Answer: Lists are indexed sequences; dictionaries are key-value pairs. "Which is faster for lookups?" Answer: Dictionaries.

Where to Go From Here

Now that you understand lists and dictionaries, check out these related topics:

Tuple vs Dictionary

Compare tuples with dictionaries for immutable vs key-value data.

Learn More →

Dictionary vs Set

Compare dictionaries with sets for key-value vs unique data.

Learn More →

List vs Set

Compare lists with sets for ordered vs unique data.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: List vs Set Next: Tuple vs Set →