Back to List

Python Lists and Dictionaries

Learn with examples how Python lists and dictionaries differ and when to use which.

Beginner
|
8min
|
Verified (2026-07)
listdictionarydata typecollectionkey-value pair
Progress0/18 (0%)

Python Lists and Dictionaries

After completing this topic

You will be able to explain the difference between lists and dictionaries and choose the appropriate one for a given situation.


Lists – Ordered Collections

A list is a container that holds multiple values in a specific order. It is created using square brackets ([]).

python
fruits = ["apple", "banana", "grape"]
# Indexing
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'grape'
# Modification
fruits[1] = "strawberry" # ['apple', 'strawberry', 'grape']
# Addition/Deletion
fruits.append("mango") # Add to the end
fruits.insert(0, "watermelon") # Insert at index 0
fruits.remove("grape") # Delete by value
del fruits[0] # Delete by index

Lists are mutable, meaning you can modify, add, or delete elements after they are created.


Iterating and Manipulating Lists

python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Iteration
for n in numbers:
print(n, end=" ") # 3 1 4 1 5 9 2 6
# Sorting
sorted_nums = sorted(numbers) # [1, 1, 2, 3, 4, 5, 6, 9] β€” original list remains unchanged
numbers.sort() # Sorts the original list in place
# Useful built-in functions
print(len(numbers)) # 8
print(sum(numbers)) # 31
print(min(numbers)) # 1
print(max(numbers)) # 9
# List comprehension β€” create a new list in a single line
squares = [x ** 2 for x in range(5)]
# [0, 1, 4, 9, 16]

List comprehension is a concise way to create new lists by condensing for loops into a single line. It's a common pattern in Python code, so it's important to become familiar with it.


Dictionaries – Key-Value Stores

Dictionaries store data as key-value pairs. They are created using curly braces ({}).

python
user = {
"name": "Kim Hoon",
"age": 30,
"email": "hoon@example.com"
}
# Accessing values
print(user["name"]) # 'Kim Hoon'
print(user.get("phone")) # None (returns None instead of an error)
# Adding/Modifying
user["phone"] = "010-1234" # Adds a new key-value pair if the key doesn't exist
user["age"] = 31 # Modifies the value if the key exists
# Deleting
del user["email"]

While lists use indices ("what's the first element?"), dictionaries use keys ("what's the value associated with 'name'?"). Keys are usually strings, but can also be numbers or tuples.


Iterating Through Dictionaries

python
scores = {"Korean": 90, "English": 85, "Math": 95}
# Iterate over keys
for subject in scores:
print(subject) # Korean, English, Math
# Iterate over keys and values simultaneously
for subject, score in scores.items():
print(f"{subject}: {score} points")
# Iterate over values only
total = sum(scores.values())
print(f"Total score: {total}") # 270
# Check if a key exists
if "Science" in scores:
print(scores["Science"])
else:
print("No Science score")

.items() returns a tuple of (key, value). .keys() returns only the keys, and .values() returns only the values.


Lists vs. Dictionaries – When to Use What

SituationChoiceReason
Order is important (1st, 2nd, 3rd...)ListIndex-based ordering
Need to look up by name ("name", "age")DictionaryAccess by key
Allow duplicate valuesList[1, 1, 2, 3] is valid
Keys must be uniqueDictionaryOverwrites if you try to insert the same key twice
Searching through 1 million itemsDictionaryKey lookup is O(1) vs. list search is O(n)

A common pattern in real-world applications is a list of dictionaries. Think of it like a database table.

python
users = [
{"name": "Kim Hoon", "age": 30},
{"name": "Lee Soo", "age": 25},
{"name": "Park Jin", "age": 35},
]
# Filter for users aged 30 or older
seniors = [u for u in users if u["age"] >= 30]

JSON files, API responses, and configuration files – these are often in the form of a "list of dictionaries". If you can freely combine these two data types, you have mastered the basics of data processing in Python.


πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...