Skip to content
PythonVariables and Basic Databeginner30 min read

Data Types in Python

Understand Python’s built-in data types, inspect objects with type(), convert between compatible types, and distinguish mutable objects from immutable ones.

In this lesson, you will learn

  • ✓Identify common built-in types: int, float, str, bool, and NoneType.
  • ✓Recognize the basic collection types list, tuple, dict, and set.
  • ✓Use type() and isinstance() to inspect objects.
  • ✓Understand the difference between a name, an object, and an object’s type.
  • ✓Convert values between compatible types using constructors such as int(), float(), and str().
  • ✓Distinguish mutable objects from immutable objects.
  • ✓Explain the difference between value equality (==) and object identity (is).

1. What Is a Data Type?

A data type describes the kind of value an object represents and the operations that are meaningful for it. For example, numbers support arithmetic, strings support text operations, and lists support operations that modify or organize collections of items.

Python is dynamically typed. You can assign an integer to a name and later assign a string to that same name. The name does not have a permanent declared type; it refers to whichever object is currently assigned to it.

This does not mean Python objects are typeless. Each object still has a type, and an operation may fail when its operands do not support that operation.

One name can refer to different types

One name can refer to different types
python
value = 25
print(value)
print(type(value))
 
value = "twenty-five"
print(value)
print(type(value))
Output
25 <class 'int'> twenty-five <class 'str'>

The integer literal 25 creates an integer object, and value refers to it. The assignment value = "twenty-five" rebinds the name to a string object. The type changes because the object referenced by value changes, not because Python permanently changes the type of a variable.

Note

An assignment statement binds a name to an object. It does not declare a permanent type for that name.

2. Integers and Floating-Point Numbers

The int type represents integers such as -8, 0, 42, and 1000. Python integers can grow beyond a fixed machine-integer range, subject to available memory and implementation limits.

The float type represents floating-point numbers, including values such as 3.5, -0.25, and 2.0. A float can have a fractional part, but a decimal point is not required in every value produced at runtime.

Floating-point numbers use finite-precision binary representation. Consequently, some decimal fractions cannot be represented exactly. This is normal floating-point behavior, not necessarily a programming mistake.

The types of the operands and the operator both matter. For example, ordinary division with / produces a float, even when both operands are integers. Floor division with // has different behavior depending on the operands.

Integer arithmetic and division

Integer arithmetic and division
python
items = 4
price = 25
total = items * price
print(total)
print(type(total))
 
average = 7 / 2
print(average)
print(type(average))
Output
100 <class 'int'> 3.5 <class 'float'>

Multiplying two integers produces the integer result 100. type(total) reports the type of the object referenced by total. The / operator performs true division, so 7 / 2 produces the float 3.5.

Note

Do not assume that every arithmetic operation returns an integer just because its inputs are integers. In particular, / performs true division.

3. Strings: The str Type

The str type represents text. String literals are commonly written using single quotes or double quotes, such as "Python" and 'Python'. The quotation marks delimit the literal in source code; they are not included in the resulting string value.

Strings are immutable. Once a string object has been created, its characters cannot be changed in place. Operations such as concatenation produce a string result, and an assignment can bind a name to that result.

Use str() when you need a string representation of a value. It converts many built-in values into text, but it does not preserve the original type information in the resulting string.

Concatenating strings

Concatenating strings
python
first_name = "Mira"
message = "Hello, " + first_name
print(message)
print(type(message))
Output
Hello, Mira <class 'str'>

The + operator concatenates two strings. The expression creates the string "Hello, Mira". The name message refers to the resulting string object.

Note

The expression "22" + "1" produces "221", because both operands are strings. It does not perform numerical addition.

4. Boolean Values: bool

The bool type has exactly two Boolean values: True and False. Capitalization matters. In Python, true and false are not the names of these built-in Boolean constants.

Comparison expressions commonly produce Boolean values. For example, 10 > 5 evaluates to True, while 10 < 5 evaluates to False.

Boolean values are useful in conditions and logical expressions. Although bool is a subclass of int in Python, beginners should treat True and False as Boolean values when expressing logical conditions rather than using them as substitutes for ordinary numbers.

A comparison produces a Boolean

A comparison produces a Boolean
python
age = 20
can_register = age >= 18
print(can_register)
print(type(can_register))
Output
True <class 'bool'>

The expression age >= 18 checks whether age is at least 18. Because age is 20, the comparison evaluates to True. The result is assigned to can_register, which refers to a Boolean object.

Note

Do not confuse the Boolean value False with the string "False", the integer 0, or None. They are different objects and types.

5. None and NoneType

None is a special singleton object commonly used to represent the absence of a value, an unavailable result, or a value that has not been supplied. Its type is NoneType.

None is not the same as 0, False, or an empty string. Those values have different meanings and types, even though they can all be false in a Boolean context.

When you specifically need to check whether a value is None, use is None or is not None. This is an appropriate use of identity comparison because Python has one None singleton.

Checking for an absent value

Checking for an absent value
python
result = None
print(result)
print(type(result))
print(result is None)
 
result = 0
print(result is None)
Output
None <class 'NoneType'> True False

Initially, result refers to the None singleton. type(result) reports NoneType. The expression result is None evaluates to True while result refers to None. After result = 0, the name refers to an integer object, so result is None evaluates to False.

Note

Use value is None for a None check. Do not use value == None as your standard style for this purpose.

6. Collection Types: list, tuple, dict, and set

Python also provides built-in collection types for grouping values. The right collection depends on how you need to access, organize, and modify the data.

A list is an ordered, mutable collection. It can contain repeated values and can be changed after creation.

A tuple is an ordered, immutable collection. It is useful when the collection of items should not be changed in place.

A dictionary (dict) stores key-value pairs. Keys must be hashable, and each key maps to a value. Dictionaries preserve insertion order in modern Python.

A set is a collection of distinct hashable elements. It is useful for membership tests and set operations. Sets do not provide positional indexing, and their display order should not be relied on.

List and tuple

List and tuple
python
numbers = [10, 20, 20]
numbers.append(30)
print(numbers)
 
coordinates = (4, 7)
print(coordinates)
print(type(coordinates))
Output
[10, 20, 20, 30] (4, 7) <class 'tuple'>

The list retains duplicate values and append(30) modifies the existing list. The tuple groups two values in a fixed sequence. The parentheses in a tuple representation do not mean the tuple can be modified; tuples are immutable.

Note

A list is mutable, but a tuple is immutable. A tuple can still contain a mutable object, such as a list; the tuple’s own item references cannot be reassigned, but that nested list can be modified.

7. Inspecting Types with type() and isinstance()

The built-in type(value) function returns the type object of a value. Printing that result commonly displays forms such as <class 'int'> or <class 'str'>.

The isinstance(value, SomeType) function checks whether a value is an instance of a type or its subclasses. It returns True or False and is often useful when code needs to validate the kind of value it receives.

For ordinary type inspection while learning Python, type() is useful. When checking whether a value belongs to a type family, isinstance() is usually more flexible.

Inspecting several types

Inspecting several types
python
count = 10
ratio = 2.5
label = "ready"
active = True
 
print(type(count))
print(type(ratio))
print(type(label))
print(type(active))
Output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

Each type() call returns the type object of the value referenced by the supplied name. The printed representation identifies the built-in type. The names count, ratio, label, and active do not need separate type declarations.

Note

If your program needs to accept subclasses as well as a base type, isinstance() is often a better choice than checking type(value) == SomeType.

8. Type Conversion

Type conversion creates or returns a value represented using a different type. Common built-in constructors include int(), float(), str(), list(), tuple(), and set(). Whether a conversion succeeds depends on the supplied value and the target type.

int("42") succeeds because the string contains valid integer text. int("hello") raises ValueError because the text cannot be interpreted as an integer.

Converting a float to an integer with int() truncates the fractional part toward zero; it does not round to the nearest integer. For example, int(4.9) returns 4 and int(-4.9) returns -4.

Conversion is not always lossless. For example, converting a list to a set removes duplicates and does not preserve the list’s positional structure.

Converting between numeric types

Converting between numeric types
python
text_number = "45"
integer_number = int(text_number)
float_number = float(integer_number)
 
print(integer_number)
print(float_number)
print(int(4.9))
print(int(-4.9))
Output
45 45.0 4 -4

int("45") converts valid integer text into the integer 45. float(45) produces the floating-point value 45.0. int(4.9) truncates toward zero rather than rounding up. int(-4.9) also truncates toward zero, producing -4.

Note

Do not assume a conversion will always succeed or preserve every detail. Invalid conversions can raise exceptions, and some conversions discard information.

9. Mutable and Immutable Objects

A mutable object can be changed after it is created. Lists, dictionaries, and sets are common mutable built-in types.

An immutable object cannot be changed in place. Integers, floats, Booleans, strings, and tuples are common examples of immutable types. An operation that appears to change an immutable value instead produces another value or object.

Assignment binds a name to an object; it does not automatically copy that object. If two names refer to the same mutable list, a mutation performed through either name is visible when the list is accessed through the other name.

Rebinding one name is different from mutating an object. Assigning a new value to one name does not automatically rebind another name that previously referred to the same object.

Two names, one list

Two names, one list
python
first = [1, 2]
second = first
 
second.append(3)
print(first)
print(second)
print(first is second)
Output
[1, 2, 3] [1, 2, 3] True

The assignment second = first makes both names refer to the same list object. second.append(3) mutates that shared list. Printing first shows the change because first refers to the same object. first is second is True because both names identify the same object.

Note

To create a shallow copy of a list, you can use a slice such as copied = original[:]. A shallow copy creates a new outer list, but nested mutable objects may still be shared.

10. Equality (==) Versus Identity (is)

The == operator compares values for equality according to the objects’ equality behavior. Two separate list objects can compare equal when they contain equal items in the same order.

The is operator checks object identity: it tells you whether two references identify the same object. It does not mean that the values merely look the same.

Use == for ordinary value comparisons. Use is None when checking specifically for None. Do not rely on whether Python reuses objects internally, such as equal small integers or strings, to determine whether is returns True.

Equal lists are not necessarily identical

Equal lists are not necessarily identical
python
first = [1, 2]
second = [1, 2]
 
print(first == second)
print(first is second)
Output
True False

Both lists contain the same values in the same order, so first == second is True. Each list literal creates a separate list object in this example. Because the objects are distinct, first is second is False.

Note

Do not replace == with is in ordinary comparisons. Identity and equality answer different questions.

11. Dry Run: Trace Names, Types, and Mutations

A dry run means tracing a program statement by statement and recording what each name refers to, which operations change an object, and what each print statement displays.

In the following example, the important detail is that second initially refers to the same list as first. The append operation mutates the list; the later assignment to second rebinds only that name.

Trace the program step by step

Trace the program step by step
python
first = [2, 4]
second = first
second.append(6)
print(first)
second = "finished"
print(first)
print(second)
print(type(second))
Output
[2, 4, 6] [2, 4, 6] finished <class 'str'>

Step 1: first = [2, 4] creates a list containing 2 and 4. first refers to that list. Step 2: second = first binds second to the same list object. No list copy is created. Step 3: second.append(6) changes the shared list to [2, 4, 6]. Both names refer to the changed list. Step 4: print(first) displays [2, 4, 6]. Step 5: second = "finished" rebinds second to a string. The original list is unchanged. Step 6: print(first) still displays [2, 4, 6], while print(second) displays finished. Step 7: type(second) reports str because second now refers to a string object.

Note

When debugging, separately track name bindings and object contents. That distinction explains many beginner mistakes involving lists and assignment.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming a variable has a permanent type.

Why it happens: Dynamic typing allows a name to refer to objects of different types over time, which can be mistaken for a variable having a fixed declared type.

Incorrect Approach
script.py
python
Assuming a variable has a permanent type.
Correct Solution
script.py
python
A name can be rebound to an object of another type. Use type(name) to inspect the type of the object it currently refers to.

Key takeaway: A name can be rebound to an object of another type. Use type(name) to inspect the type of the object it currently refers to.

#2 Assuming "22" is the integer 22.

Why it happens: Quotation marks make digits a string value; arithmetic requiring an integer needs an explicit conversion such as int().

Incorrect Approach
script.py
python
Assuming "22" is the integer 22.
Correct Solution
script.py
python
Quoted digits form a string. Use int("22") when an integer is required, and handle invalid input when conversion may fail.

Key takeaway: Quoted digits form a string. Use int("22") when an integer is required, and handle invalid input when conversion may fail.

#3 Confusing 0, False, None, an empty string, and the string "False".

Why it happens: Several distinct values are falsy, but the non-empty string "False" is truthy because it is text rather than the Boolean value False.

Incorrect Approach
script.py
python
Confusing 0, False, None, an empty string, and the string "False".
Correct Solution
script.py
python
These are different values and types. Some are false in a Boolean context, while the non-empty string "False" is truthy.

Key takeaway: These are different values and types. Some are false in a Boolean context, while the non-empty string "False" is truthy.

#4 Assuming every decimal fraction is stored exactly as a float.

Why it happens: Decimal fractions such as 0.1 often have no exact finite binary floating-point representation, so their stored values can be approximations.

Incorrect Approach
script.py
python
Assuming every decimal fraction is stored exactly as a float.
Correct Solution
script.py
python
Floating-point numbers have finite precision. Some decimal fractions have no exact finite binary representation.

Key takeaway: Floating-point numbers have finite precision. Some decimal fractions have no exact finite binary representation.

#5 Using is to compare ordinary values.

Why it happens: The is operator checks object identity rather than ordinary value equality; using it for numeric or string comparisons can produce misleading results.

Incorrect Approach
script.py
python
Using is to compare ordinary values.
Correct Solution
script.py
python
Use == for value equality. Use is when identity matters, especially for checking value is None.

Key takeaway: Use == for value equality. Use is when identity matters, especially for checking value is None.

#6 Assuming assignment copies a mutable object.

Why it happens: Assigning another name to a mutable object creates an alias, not an independent copy, so in-place changes may appear through both names.

Incorrect Approach
script.py
python
Assuming assignment copies a mutable object.
Correct Solution
script.py
python
Assignment binds another name to the same object. Make an explicit copy when you need a separate outer list or dictionary.

Key takeaway: Assignment binds another name to the same object. Make an explicit copy when you need a separate outer list or dictionary.

#7 Assuming int(4.9) rounds to 5.

Why it happens: int() converts a float by truncating toward zero rather than rounding to the nearest integer.

Incorrect Approach
script.py
python
Assuming int(4.9) rounds to 5.
Correct Solution
script.py
python
int() truncates the fractional part toward zero. Use round() if rounding is the operation you intend.

Key takeaway: int() truncates the fractional part toward zero. Use round() if rounding is the operation you intend.

#8 Assuming a set preserves duplicate values or supports numeric indexing.

Why it happens: Sets store unique hashable elements and do not support positional indexing; lists are the suitable choice when order, duplicates, or index access matter.

Incorrect Approach
script.py
python
Assuming a set preserves duplicate values or supports numeric indexing.
Correct Solution
script.py
python
Sets keep distinct hashable elements and do not provide positional indexing. Use a list when order and repeated items matter.

Key takeaway: Sets keep distinct hashable elements and do not provide positional indexing. Use a list when order and repeated items matter.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a data type in Python?
Answer:
A data type identifies the kind of object a value represents and the operations it supports. Examples include int for integers, float for floating-point numbers, str for text, bool for Boolean values, and list for mutable sequences.
Q2:What does dynamically typed mean in Python?
Answer:
Python names do not require a declared type before assignment. A name can refer to an integer object and later be rebound to a string object. The objects themselves still have types, and operations must be valid for their operands.
Q3:What is the difference between int and float?
Answer:
int represents integers, while float represents finite-precision floating-point values. A float can represent fractional values, but some decimal fractions cannot be represented exactly in binary. Ordinary division with / produces a float.
Q4:What is the difference between type() and isinstance()?
Answer:
type(value) returns the exact type object of the value. isinstance(value, SomeType) checks whether the value is an instance of SomeType or a subclass. isinstance() is often more suitable for type checks that should accept subclasses.
Q5:What is the difference between mutable and immutable objects?
Answer:
Mutable objects can be changed in place; lists, dictionaries, and sets are common examples. Immutable objects cannot be changed in place; integers, floats, strings, Booleans, and tuples are examples. Operations on immutable values produce results rather than modifying the original object.
Q6:What is the difference between == and is?
Answer:
== compares values for equality according to the objects’ equality behavior. is checks whether two references identify the same object. Two separate lists can be equal without being identical. Use is None when checking for None.
Q7:Does assigning one list to another name copy it?
Answer:
No. If second = first, both names refer to the same list object. Mutating the list through either name is visible through both. Rebinding second to a new list changes only what second refers to. Use an explicit copy when a separate outer list is required.
Q8:What is type conversion, and what can go wrong?
Answer:
Type conversion creates or returns a value represented using another type, such as int("42") or str(42). A conversion may fail if the input is invalid; for example, int("hello") raises ValueError. Some conversions also lose information, such as int(4.9), which returns 4.
Q9:What are the differences between a list, tuple, dictionary, and set?
Answer:
A list is an ordered, mutable sequence that permits duplicates. A tuple is an ordered, immutable sequence. A dictionary maps hashable keys to values and preserves insertion order in modern Python. A set stores distinct hashable elements and does not support positional indexing.
Q10:Why should is not be used to compare ordinary values?
Answer:
Identity and value equality are different questions. Two equal values may be held by separate objects, and object reuse can depend on implementation details. Use == for ordinary value comparisons and is for identity checks where identity is intended, especially value is None.

Key takeaways

  • Every Python object has a type, even though names do not need declared types.
  • Common built-in types include int, float, str, bool, and NoneType.
  • Lists, tuples, dictionaries, and sets serve different collection needs.
  • Use type() to inspect an object’s exact type and isinstance() for type-family checks.
  • Use int(), float(), and str() to convert compatible values, remembering that conversions can fail or lose information.
  • Lists, dictionaries, and sets are mutable; strings, numbers, Booleans, and tuples are immutable.
  • Assignment binds names to objects; it does not automatically copy mutable objects.
  • Use == for value equality and is None when checking for None.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: