1. Home
  2. Blog
  3. Software Development

Software Development

Python Lists vs Tuples vs Sets vs Dictionaries: When to Use Each

Python list vs tuple vs set vs dictionary, answered with a decision table, measured lookup timings and short examples you can run.

8 min read
Python list vs tuple vs set vs dictionary: when to use each

Key takeaways

  • List: ordered, changeable, allows duplicates. Tuple: ordered, fixed. Set: unique items, fast membership. Dict: key to value lookup.
  • Checking x in a set or dict is hash based and stays fast; on a list or tuple it scans item by item.
  • Tuples and frozensets are hashable, so they can be dict keys or set members; lists and sets cannot.
  • Pick the structure from the question you ask most often: order, uniqueness or lookup by key.

The Python list vs tuple vs set question comes up in every beginner project, and the answer is shorter than most tutorials make it. Each structure is built for one kind of question, and dictionaries cover a fourth.

Choose well in any Python list vs tuple vs set decision and your code gets faster and clearer. Choose badly and you end up de-duplicating lists by hand or scanning a million items to check one name.

This guide compares lists, tuples, sets and dictionaries side by side, shows real timings from a quick benchmark, and finishes with a decision table plus the mistakes testers and developers make most often. If you are new to the language, start with our Python tutorial for beginners.

Python list vs tuple vs set: quick comparison

Feature List Tuple Set Dict
Syntax [1, 2] (1, 2) {1, 2} {"a": 1}
Ordered Yes Yes No guaranteed order Yes, insertion order
Changeable (mutable) Yes No Yes Yes
Duplicates Allowed Allowed Not allowed Keys unique
Index by position Yes Yes No By key
Can be a dict key No Yes, if items are hashable No No
Typical use Sequence you edit Fixed record Unique items, membership Lookup by key

Dictionaries keep insertion order since Python 3.7. Sets do not promise any order, so never rely on the order you see when printing one. The Python docs describe all four in the data structures tutorial.

Lists: the default for ordered, changeable data

Use a list when you need a sequence you will add to, remove from or sort. Test data rows, API results and queued tasks are typical.

users = ["asha", "ben", "asha"]
users.append("chen")
users.sort()
print(users)        # ['asha', 'asha', 'ben', 'chen']
print(users[0])     # asha

Lists are flexible, but that flexibility has a cost. Looking up a value with in checks items one by one, so it slows down as the list grows.

Tuples: a fixed record

A tuple says “these values belong together and will not change”. Coordinates, database rows and function return values fit well.

point = (12.5, 77.6)
lat, lon = point              # unpacking
def min_max(nums):
    return min(nums), max(nums)   # returns a tuple
low, high = min_max([4, 1, 9])

Because tuples cannot change, Python can use them as dictionary keys, provided every item inside is hashable too. A tuple holding a list is not.

Tip: a one-item tuple needs a trailing comma: (5,). Without it, (5) is just the number 5.

Sets: uniqueness and fast membership

Use a set to remove duplicates or to ask “is this item present?” many times. Sets also support maths-style operations.

a = {"login", "search", "cart"}
b = {"cart", "checkout"}
print(a | b)    # union
print(a & b)    # intersection: {'cart'}
print(a - b)    # difference
print(len(set([3, 3, 1, 1, 2])))   # 3

Note that {} creates an empty dictionary. Use set() for an empty set. If you need an immutable set, use frozenset.

Dictionaries: lookup by key

If you often ask “what is the value for this name?”, use a dict.

prices = {"apple": 1.2, "pear": 0.9}
prices["kiwi"] = 1.5
print(prices.get("mango", "n/a"))   # n/a
for name, price in prices.items():
    print(name, price)

Dictionaries are the backbone of JSON handling, so they appear constantly in API work; see what is an API for the request side.

Python list vs tuple vs set speed: a real timing

I ran a worst-case lookup (the last item) on a collection of 100,000 integers using Python 3.13.6 on a laptop and timeit:

Structure Time for 99999 in x
List about 1,300 microseconds
Tuple about 1,150 microseconds
Set about 0.1 microseconds
Dict about 0.04 microseconds

Your numbers will differ, but the gap is the point: hash-based lookup is roughly four orders of magnitude faster at this size. The official time complexity page lists the average cost as O(1) for sets and dicts and O(n) for lists and tuples. Memory differs too: on the same machine, a three-item tuple used 64 bytes versus 88 for a list, and 216 bytes for a set, so small tuples are cheaper to hold in large numbers.

Python list vs tuple vs set: which one should you use?

Your need Use
Ordered items you will edit List
Fixed group of values, function return Tuple
Remove duplicates, fast “is it in there?” Set
Look up a value by name or ID Dict
Composite key like (x, y) Tuple as dict key
Keep order and remove duplicates list(dict.fromkeys(items))

Common mistakes

  • Using a list for membership tests inside a loop. Convert to a set first.
  • Expecting set order. Sort the result if order matters.
  • Mutable default arguments. def f(x=[]) shares one list across calls; use None instead.
  • Putting a list inside a set. It raises TypeError: unhashable type; use a tuple.
  • Editing a list while looping over it. Loop over a copy or build a new list.

When you test code built on a Python list vs tuple vs set choice, a parameterised test is a handy way to check them; our guide to writing test cases shows the format.

Final thoughts

For the Python list vs tuple vs set decision, ask what you do most: edit a sequence, keep a fixed record, check membership or look up by key. Start with a list, switch to a set or dict when lookups slow you down, and use tuples for data that should not change. That rule covers most real code.

Frequently asked questions

What is the main difference between a list and a tuple in Python?

A list can be changed after creation, a tuple cannot. Tuples are therefore hashable when their items are, so they can be dictionary keys.

Are Python sets ordered?

No. Sets do not guarantee any order. Dictionaries, in contrast, keep insertion order since Python 3.7.

When should I use a set instead of a list?

Use a set when you need unique items or you check membership often. Set lookups take constant time on average, while list lookups scan every item.

Can a tuple contain a list?

Yes, but the tuple is then not hashable, and the list inside can still change. Avoid it if you need a dictionary key.

How do I remove duplicates but keep order?

Use list(dict.fromkeys(items)), which keeps the first occurrence of each item in insertion order.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →