In Python, data types are classified into primitive (or basic) and non-primitive (or composite) types. Let’s explore each category in detail with examples.
Primitive Data Types #
Primitive data types are the most basic types of data. They are the building blocks for data manipulation and are usually built into the language.
- Integer (int)
- Whole numbers, positive or negative, without decimals.
- Example:
age = 25
- Float (float)
- Numbers with decimal points.
- Example:
temperature = 36.6
- Boolean (bool)
- Represents one of two values:
True
orFalse
. - Example:
is_student = True
- Represents one of two values:
- String (str)
- A sequence of characters enclosed within single or double quotes.
- Example:
name = "Alice"
Non-Primitive Data Types #
Non-primitive data types are more complex data structures. They can hold multiple values and are derived from primitive data types.
- List
- Ordered collection of items, which can be of different types.
- Mutable, meaning their elements can be changed.
- Example: code
fruits = ["apple", "banana", "cherry"]
- Tuple
- Ordered collection of items similar to a list, but immutable.
- Example: code
coordinates = (10.0, 20.0)
- Set
- Unordered collection of unique items.
- Example: code
unique_numbers = {1, 2, 3, 4, 5}
- Dictionary
- Collection of key-value pairs, where each key is unique.
- Example:
student = {"name": "Bob", "age": 22, "is_student": True}
Examples of Using These Data Types #
# Primitive data types
num = 10 # int
pi = 3.14159 # float
is_valid = False # bool
greeting = "Hello" # str
# Non-Primitive data types
colors = ["red", "green", "blue"] # list
point = (4, 5) # tuple
unique_letters = {'a', 'b', 'c'} # set
person = {"name": "Alice", "age": 30} # dictionary
# Accessing elements in non-primitive types
print(colors[1]) # Output: green
print(point[0]) # Output: 4
print('a' in unique_letters) # Output: True
print(person["name"]) # Output: Alice
Summary #
- Primitive Data Types:
int
,float
,bool
,str
. - Non-Primitive Data Types:
list
,tuple
,set
,dictionary
.
Primitive types store single values, whereas non-primitive types store collections of values. This distinction is important for understanding how data is managed and manipulated in Python.