Python provides a variety of built-in data types. In Python, since everything is an object, data types are actually classes; and the variables are instances of the classes. A data type defines the type of a variable and allows us to store and manipulate different kinds of data.
In Python, similar to any programming language, different operations can be performed over different types of data types, some of which are common with other datatypes while some can be very specific to that particular datatype.
In this beginner-friendly guide, we’ll explore some of the most commonly used built-in data types in Python with examples.
1. Built-in Data Types: A Quick Overview
Python has the following data types built-in by default. We will learn about these types in more detail in next section.
Category | Data types / Class names |
---|---|
Text/String Types | str |
Numeric Types | int , float , complex |
Sequence Types | list , tuple , range |
Mapped Types | dict |
Set Types | set , frozenset |
Boolean Types | bool |
Binary Types | bytes , bytearray , memoryview |
None Type | None |
2. String Type
The string can be defined as the sequence of characters enclosed in single, double, or triple quotes. The triple quotes (“””) can be used for writing multi-line strings.
name = "Alice"
greeting = 'Hello, World!'
We can perform various text operations on these strings, such as concatenation.
message = name + ", " + greeting # Concatenation
print(message) #Prints Alice, Hello, World!
substring = message[0:5]
print(substring) #Prints Alice
3. Numeric Types
These are number types. They are created when a number is assigned to a variable.
int
holds signed integers of non-limited length.float
holds floating precision numbers, and they are accurate upto 15 decimal places.complex
– A complex number contains the real and imaginary parts.
x = 2
x = int(2)
y = 2.5
y = float(2.5)
z = 100+3j
z = complex(100+3j)
4. Sequence Types
Sequence types in Python are data types that represent ordered collections of elements. These elements can be of any data type, including numbers, strings, or even other sequences.
Python provides several built-in sequence types, each with its own characteristics and use cases.
- A list is an ordered sequence of some data written using square brackets(
[ ]
) and commas(,
). A list can contain data of different types. - A tuple is similar to the
list
– excepttuple
is a read-only data structure, and we can’t modify the size and value of the items of a tuple. Also, items are enclosed in parentheses(, )
. - A range can be considered as
sublist
, taken out of alist
using the slice operator.
my_list = [1, 'apple', 3.14, [4, 5]]
my_tuple = (1, 'apple', 3.14)
my_range = range(1, 6) # Represents numbers from 1 to 5 (inclusive)
5. Mapping Type
A mapping type helps in storing key-value pairs. In Python, a dict or dictionary is an ordered set of a key-value pair of items. A key can hold any primitive data type, whereas the value is an arbitrary Python object.
The entries in the dictionary are separated with the comma and enclosed in the curly braces {, }
.
person = {'name': 'Alice', 'age': 30}
grades = {'math': 95, 'history': 85, 'science': 90}
6. Set Types
The set in Python can be defined as the unordered collection of unique items enclosed within the curly braces{, }
. The important point to note is that the set elements can not be duplicates. Unlike list
, there is no index
for set elements. It means we can only loop through the elements of the set
.
The frozen sets are the immutable form of the normal sets. It means we cannot remove or add any item to the frozen set.
num_set = {1, 2, 3, 4, 5} char_set = {'a', 'b', 'c'} immutable_set = frozenset([1, 2, 3])
7. Boolean Type
The bool values are the two constant objects False
and True
. They are used to represent truth values. In numeric contexts, they behave like the integers 0 and 1, respectively.
x = True
y = False
print(x) #True
print(y) #False
print(bool(1)) #True
print(bool(0)) #False
8. Binary Types
In Python, bytes
, bytearray
, and memoryview
are used to work with binary data and memory views of binary data. They are essential for tasks like handling binary files, network communication, and low-level data manipulation.
The bytes is an immutable sequence type to represent sequences of bytes (8-bit values). Each element in a bytes
object is an integer in the range [0, 255]. We should use it for handling binary data, such as reading/writing files, network communication, or encoding/decoding data.
Bytes are defined using the b
prefix followed by a sequence of bytes enclosed in single or double quotes.
my_bytes = b'Hello, World!'
The bytearray is similar to bytes but unlike bytes
, bytearray
objects can be modified after creation. We use this to modify binary data in place, such as when processing binary files or network protocols.
Bytearrays are defined using the bytearray()
constructor, which accepts an iterable.
my_bytearray = bytearray([72, 101, 108, 108, 111])
A memoryview
type to create a “view” of memory containing binary data. It doesn’t store the data itself but provides a view into the memory where the data is stored. These are handy for efficiently manipulating large amounts of data without copying it.
Memory views are typically used in advanced scenarios where direct memory manipulation is required, such as in high-performance applications.
data = bytearray([1, 2, 3, 4, 5])
mem_view = memoryview(data)
9. None Type
The None represents a special value indicating the absence of a value.
no_value = None
10. How to Check the Data Type of a Variable?
In Python, the type()
function can be used to get the data type of any object. Let us see an example.
x = 5
print(type(x)) # <class 'int'>
y = 'howtodoinjava.com'
print(type(y)) # <class 'str'>
11. Conclusion
The above-discussed Python data types provide the building blocks for more complex data structures and operations. Understanding their purpose and usage will make us a better programmer.
Happy Learning !!
Comments