Last modified: Sep 07, 2026
How to Store Data in Python
Storing data is the first step in any Python program. It is how you keep values for later use. Python offers many ways to do this. Each method has its own strengths. This guide will show you the core options. You will learn about simple variables and complex structures. We will also cover file storage for permanent data. By the end, you will know which tool fits your task.
Simple Variables for Single Values
The simplest way to store data is in a variable. Think of it as a labeled box. You put a value inside and give it a name. Python then remembers that value for you. You can store numbers, text, or true/false values.
To create a variable, use the equals sign. The name goes on the left. The value goes on the right. Python figures out the type automatically. You do not need to declare it. This makes code fast to write.
Here is a basic example. We store a name and an age. Then we print them out. Notice how easy it is to change the value later. You just assign a new value to the same name.
# Storing simple data types
name = "Alice" # Store a string
age = 30 # Store an integer
height = 5.6 # Store a float
is_student = True # Store a boolean
# Print the stored data
print(name)
print(age)
print(height)
print(is_student)
# Change the value of age
age = 31
print("New age:", age)
Alice
30
5.6
True
New age: 31
Variables are perfect for temporary data. They only exist while the program runs. Once the program stops, the data is gone. For long-term storage, you need files or databases. But for now, variables are your building blocks. They are the foundation of all other storage methods.
Lists for Ordered Collections
Often you need to store many related items. A list is ideal for this. It keeps items in a specific order. You can add, remove, or change items at any position. Lists are mutable, meaning they can grow or shrink. This makes them very flexible.
To create a list, use square brackets. Separate items with commas. Lists can hold different data types. You can mix numbers and strings. To access an item, use its index. The first item has index 0. Python uses zero-based indexing.
The append() method adds an item to the end. The remove() method deletes a specific value. Let us see this in action. We build a list of fruits. Then we add one and remove another.
# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
print("Original list:", fruits)
# Add a new fruit to the end
fruits.append("orange")
print("After append:", fruits)
# Remove the banana
fruits.remove("banana")
print("After remove:", fruits)
# Access the first item
first_fruit = fruits[0]
print("First fruit:", first_fruit)
# Check the length of the list
print("Number of fruits:", len(fruits))
Original list: ['apple', 'banana', 'cherry']
After append: ['apple', 'banana', 'cherry', 'orange']
After remove: ['apple', 'cherry', 'orange']
First fruit: apple
Number of fruits: 3
Lists are great for sequences of data. Think of a to-do list or a series of test scores. You can loop through a list easily. This helps with tasks like summing numbers. For more advanced data work, you might use libraries like Pandas. If you want to dive deeper, check out our guide on Python Data Analysis. It shows how to handle larger datasets efficiently.
Dictionaries for Key-Value Pairs
Sometimes you need to store data with labels. A dictionary is perfect for this. It stores pairs of keys and values. Each key must be unique. You use the key to access its value. This is like a real dictionary where words map to definitions.
To create a dictionary, use curly braces. Write key-value pairs separated by colons. Keys are often strings, but they can be numbers. Values can be any data type. This makes dictionaries very powerful for structured data.
You can access a value by its key inside square brackets. To add a new pair, just assign a value to a new key. The get() method is safer than direct access. It returns a default value if the key is missing. This prevents errors.
# Creating a dictionary for a person
person = {
"name": "Bob",
"age": 25,
"city": "New York"
}
print("Original dictionary:", person)
# Access a value using its key
print("Name:", person["name"])
# Add a new key-value pair
person["job"] = "Engineer"
print("After adding job:", person)
# Use get() to safely access a key
salary = person.get("salary", "Not available")
print("Salary:", salary)
# Update an existing value
person["age"] = 26
print("Updated age:", person["age"])
Original dictionary: {'name': 'Bob', 'age': 25, 'city': 'New York'}
Name: Bob
After adding job: {'name': 'Bob', 'age': 25, 'city': 'New York', 'job': 'Engineer'}
Salary: Not available
Updated age: 26
Dictionaries are excellent for representing real-world objects. A user profile, a product, or a settings file can all be a dictionary. They make your code readable and organized. When you progress in Python, you will use dictionaries everywhere. They are essential for data manipulation. For more practice, our Beginner's Guide covers these concepts in more depth.
Sets for Unique Items
What if you need to store items with no duplicates? A set is the answer. It automatically removes any repeats. Sets are unordered. This means you cannot access items by index. But you can check if an item exists very quickly. This makes sets great for membership tests.
To create a set, use curly braces or the set() function. If you pass a list with duplicates, the set will keep only unique values. You can add items with the add() method. To remove an item, use discard() which does not error if the item is missing.
Sets also support mathematical operations. You can find the union, intersection, or difference between two sets. This is useful for comparing groups of data. Let us see a simple example.
# Creating a set with duplicates
numbers = {1, 2, 2, 3, 4, 4, 5}
print("Set with unique values:", numbers)
# Add a new item
numbers.add(6)
print("After adding 6:", numbers)
# Remove an item if it exists
numbers.discard(3)
print("After removing 3:", numbers)
# Check membership
print("Is 2 in the set?", 2 in numbers)
# Create two sets for comparison
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print("Union:", set_a.union(set_b))
print("Intersection:", set_a.intersection(set_b))
Set with unique values: {1, 2, 3, 4, 5}
After adding 6: {1, 2, 3, 4, 5, 6}
After removing 3: {1, 2, 4, 5, 6}
Is 2 in the set? True
Union: {1, 2, 3, 4, 5}
Intersection: {3}
Sets are perfect for removing duplicates from a list. They are also fast for large data checks. If order matters, convert the set back to a list. Use list(my_set) to do this. Sets are a hidden gem in Python. They save time and memory.
Storing Data in Files
Variables, lists, and dictionaries only store data in memory. This data disappears when the program ends. To keep data permanently, you must write it to a file. Python makes file handling simple with built-in functions. You can store text or binary data.
The most common way is to use the open() function. You specify the file name and the mode. Mode 'w' writes to a file, overwriting existing content. Mode 'a' appends to the end. Mode 'r' reads the file. Always close the file after using it. A better way is to use a 'with' statement. This automatically closes the file for you.
For structured data, you can use the JSON format. The json module converts Python objects to text. This is excellent for dictionaries and lists. It makes saving and loading data very easy. Let us see how to write and read a JSON file.
import json
# Data to store
data = {
"name": "Charlie",
"age": 28,
"hobbies": ["reading", "coding", "hiking"]
}
# Write data to a JSON file
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
print("Data saved to data.json")
# Read data back from the file
with open("data.json", "r") as file:
loaded_data = json.load(file)
print("Data loaded from file:")
print(loaded_data)
# Access a value from the loaded data
print("Name from file:", loaded_data["name"])
Data saved to data.json
Data loaded from file:
{'name': 'Charlie', 'age': 28, 'hobbies': ['reading', 'coding', 'hiking']}
Name from file: Charlie
File storage is essential for any real application. You can save user settings, game progress, or analysis results. For large datasets, you might use CSV or Excel files. Python has libraries like Pandas for that. If you are preparing for a job, you should understand these basics. Our Interview Questions Guide often tests this knowledge. Practice writing and reading files until it becomes second nature.
Conclusion
Storing data is a core skill in Python. You have many tools at your disposal. Use variables for single values. Use lists for ordered collections. Use dictionaries for labeled data. Use sets for unique items. Use files for permanent storage.
Start with simple variables. Then move to lists and dictionaries. They will solve most of your problems. As you grow, you will find the right structure for each task. Do not be afraid to experiment. Write small programs to test each method. This hands-on practice is the best way to learn.
Remember that Python is forgiving. You can change data types easily. You can convert between structures. The key is to choose the simplest tool that works. This keeps your code clean and efficient. Good luck with your data storage journey.