Python Variable Data Types: Numbers, Strings, Lists, Tuples, and Dictionaries
Learn how Python variables refer to values, how dynamic typing works, and how to create, access, modify, inspect, and convert numbers, strings, lists, tuples, and dictionaries.
Python programs store information in variables. A variable is a name that refers to a value or object. The value's data type describes what kind of data it is and determines which operations are valid and how the data behaves.
For example, numbers can be added, strings can be joined, and list elements can be changed. Learning the basic data types helps you choose the right representation for each problem.
Variables, values, and data types
Assignment uses the equals sign (=) to bind a name to a value:
count = 5
message = "Hello"
Here, count and message are variable names. The values are 5 and "Hello". A name is not the same thing as the value it refers to: the name is a label used by your code, while the value is the data stored or referenced.
Python is dynamically typed. A name is not permanently restricted to one data type, so it can later refer to a value of another type:
value = 5
value = "five"
At the second assignment, value refers to a string instead of an integer. The type still matters because it controls behavior. Adding two integers is valid, while trying to use an integer as if it were a string may produce an error.
Five foundational data-type categories
This beginner-focused grouping covers five commonly used categories:
- Numbers: quantities and calculations. Common types include
int,float, andcomplex. - Strings: text written as an ordered sequence of characters. The common type is
str. - Lists: ordered collections that can be changed. The type is
list. - Tuples: ordered collections intended to remain fixed. The type is
tuple. - Dictionaries: mutable mappings from unique keys to values. The type is
dict.
Strings, lists, and tuples are ordered sequences, so their contents are accessed by numeric positions called indexes. A dictionary is a key-based mapping: you retrieve a value using a meaningful key rather than a positional index. These five categories are a useful starting point, not a complete inventory of Python's built-in types.
Common literal forms
A literal is source-code notation that writes a value directly:
Numeric values
Integers
An integer, or int, is a whole number without a fractional part. Python 3 uses int for integers of arbitrary precision; there is no separate standard long type.
count = 5
large_number = 10 ** 100
result = count + 3
Floating-point numbers
A floating-point number, or float, represents a decimal value:
price = 19.99
total = price * 2
Floating-point calculations can have small rounding differences because many decimal fractions cannot be represented exactly in binary. For ordinary introductory calculations, float is usually appropriate.
Complex numbers
A complex number, or complex, has real and imaginary components. Python writes the imaginary component with a lowercase j:
signal = 3 + 4j
Inspecting numeric types
print(type(count)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(signal)) # <class 'complex'>
For more arithmetic practice, see Python arithmetic operators and numeric variables.
Strings
A string, or str, is an ordered, immutable sequence of text characters. You can create one with single or double quotation marks:
message = "This is text"
other_message = 'This is also text'
Choose the quote style that makes the contents easy to read. For example, double quotes allow an apostrophe without escaping it:
sentence = "Python's syntax is readable"
quote = 'She said "hello"'
Characters use zero-based indexing. The first character is at index 0:
message = "Hello"
first_character = message[0] # "H"
length = len(message) # 5
Strings are immutable, meaning they cannot be changed after creation. Assigning to an individual character is invalid. Create a new string instead:
word = "cat"
word = "b" + word[1:] # creates "bat"
Joining strings with + is called concatenation. For a deeper introduction, read what strings are and how to access individual characters.
Lists
A list is an ordered, mutable collection. List literals use square brackets with comma-separated elements:
numbers = [5, 3, 2, 1]
first_number = numbers[0] # 5
List elements may have different types, although using a consistent element type is often clearer:
mixed = [42, "answer", 3.14]
Because lists are mutable, you can replace an item or add an item after creation:
numbers[1] = 10
numbers.append(8)
print(numbers) # [5, 10, 2, 1, 8]
Use a list when an ordered collection may grow, shrink, or have its elements changed. See what lists are and how to modify lists.
Tuples
A tuple is an ordered, immutable collection. Tuples are commonly written with parentheses and comma-separated values:
coordinates = (2, 4, 5)
x_coordinate = coordinates[0] # 2
Like strings, tuples cannot be changed in place. They are useful for fixed groupings such as coordinates, dimensions, or days of the week:
dimensions = (1920, 1080)
days = ("Monday", "Tuesday", "Wednesday")
A one-element tuple requires a trailing comma. Parentheses alone are not enough:
not_a_tuple = (5) # int
single_item = (5,) # tuple
Dictionaries
A dictionary, or dict, is a mutable mapping from unique keys to values. A key is an identifier used to retrieve its associated value. Dictionary literals use curly braces, colons between keys and values, and commas between pairs:
item = {"color": "blue", "size": "small"}
item_color = item["color"] # "blue"
Dictionary access is key-based, not positional. Add a new pair or update an existing key by assigning through that key:
item["size"] = "medium" # updates an existing key
item["in_stock"] = True # adds a new key-value pair
Keys must be hashable, which means they are eligible for dictionary lookup. Common key types include strings, integers, and tuples. Values may have any type, including another list or dictionary.
Direct bracket lookup raises KeyError if the key is absent. The get() method can return a fallback instead:
color = item["color"]
missing_size = item.get("weight", "unknown")
Use dictionaries for labeled properties or lookups by meaningful names, such as record["name"], rather than trying to use a numeric position. Learn more about Python dictionaries and adding dictionary key-value pairs.
Accessing collection contents
Indexing means using a zero-based numeric position in an ordered sequence. Strings, lists, and tuples use indexes:
letters = "abcd"
values = ["zero", "one", "two"]
coordinates = (10, 20)
letters[0] # "a"
values[0] # "zero"
coordinates[1] # 20
The first item always has index 0, the second has index 1, and so on. Dictionaries use keys instead:
numbers = [5, 3, 2]
item = {"color": "blue"}
sequence_item = numbers[0]
mapped_item = item["color"]
An invalid sequence index raises IndexError. A missing dictionary key raises KeyError. These errors identify different access problems.
Checking and converting types
Use type() to inspect the type of a value:
type(numbers) # list
type("hello") # str
Use isinstance() when you need to check whether a value has a particular type:
price = 19.99
isinstance(price, float) # True
isinstance(price, int) # False
Common conversion functions create a value of a requested type when the source is compatible:
age = int("42")
amount = float("19.99")
label = str(42)
letters = list("cat")
point = tuple([2, 4])
record = dict([("name", "Ava")])
Not every value can be converted to every type. For example, int("blue") raises ValueError because the text does not represent an integer. Validate or clean input before converting it.
List versus tuple versus dictionary
Choosing the correct data type
- Choose numbers for quantities, measurements, and calculations.
- Choose strings for names, messages, labels, and other text.
- Choose a list for an ordered collection that may change.
- Choose a tuple for an ordered grouping intended to remain fixed.
- Choose a dictionary when values should be found through meaningful labels or keys.
Common mistakes and troubleshooting
- Using index 1 for the first item: Python starts sequence indexes at 0, so use
collection[0]. - Changing a string character or tuple element: both types are immutable. Create a new value, or use a list when modification is required.
- Using positional access on a dictionary: dictionaries use keys, such as
record["name"], not list-style positions. - Getting
KeyError: the requested dictionary key is absent. Check the spelling and key type, inspect available keys, or useget()with a suitable fallback. - Getting
IndexError: an index is outside the valid range. Checklen(collection)and use an index from0throughlen(collection) - 1. - Unexpected one-item tuple behavior: use
(value,); the comma creates the tuple. - Looking for a separate long integer type: Python 3 uses
intfor whole numbers of arbitrary size. - Getting
ValueErrorduring conversion: the source cannot be interpreted as the target type, such asint("blue").
Key points to remember
- A variable is a name bound to a value or object; the name and value are distinct.
- Python uses dynamic typing, so a name can later refer to a different type.
- Strings and tuples are immutable; lists and dictionaries are mutable.
- Strings, lists, and tuples use zero-based indexes.
- Dictionaries retrieve values with unique, hashable keys.
- Use
type()to inspect a type,isinstance()to test a type, and conversion functions only with compatible values.