Python Data Types: A Beginner's Guide with Examples
What Are Data Types in Python?
In Python, data types define the kind of value a variable can hold. Think of them as different containers for different kinds of information - a number container, a text container, a list container, and so on.
The best part? Python is dynamically typed. You don't need to declare what type a variable is. Python figures it out automatically:
Example:
This simplicity makes Python one of the easiest programming languages to learn.
Python's data types can be broadly classified into several categories:
Text Type:
strNumeric Types:
int,float,complexSequence Types:
list,tuple,rangeMapping Type:
dictSet Types:
set,frozensetBoolean Type:
boolBinary Types:
bytes,bytearray,memoryviewNone Type:
NoneType
Let's explore each of these in detail.
1. Numeric Types
- Python excels at handling numbers with three primary numeric types.
A) int (Integer)
Integers
are whole numbers, positive or negative, without a decimal point. Unlike many
languages, Python's integers have arbitrary precision, meaning they
can grow to an unlimited size, limited only by your system's memory.
B) float(Floating-Point
Number)
For
applications requiring exact decimal representation (e.g., financial
calculations), the decimal module should be used instead of float.
c) complex (Complex Number)
Complex numbers are written with a literal j or J representing the imaginary part. They are used in scientific computing and engineering applications.
Strings in Python are immutable sequences of
Unicode characters. They can be defined using single quotes ('), double quotes
("), triple single quotes ('''), or triple double quotes (""").
The triple-quoted forms are excellent for multi-line strings.
- Immutability: Once a string is created, its contents
cannot be changed. Any operation that modifies a string creates a new
string.
- Indexing and Slicing: Strings are sequences,
so individual characters can be accessed using zero-based indexing and
slices.
- Rich Set of Methods: Python provides a vast
library of string methods like
.upper(),.lower(),.split(),.join(),.strip(),and many more.
Sequences are ordered collections of items,
where each item can be accessed by its index.
A) list(List)
Lists are mutable, ordered
sequences that can hold a mix of data types. They are one of the most versatile
and commonly used data structures in Python.
i) How to create a list
B) tuple (Tuple)
- A tuple is a built-in data type used to store a collection of items.
- It is similar to a list, but with one critical difference: Tuples are immutable.
- Ordered: Items have a defined order, and that order will not change.
- Immutable: Once created, elements cannot be added, removed, or changed.
- Heterogeneous: A tuple can contain elements of different data types (integers, strings, lists, etc.).
- Indexed: We can access items using their position (index)
i) Creating Tuples
- Tuples are typically created by placing a sequence of values separated
by commasinside parentheses ( ).
ii) Creating a Single-Item Tuple in Python
iii) Access Tuple Items
Tuple elements can be accessed by:
- Positive Indexing: Starts from 0.
- Negative Indexing: Starts from-1 (the last item).
- Slicing: [start:stop:step]
iv) tuple() Constructor
- We can convert lists or strings into tuples
- We can also Convert string to tuple
v) Delete Tuples
- We can not delete individual items of a tuple. However, we can delete the tuple itself using the del statement.
vi) Built-in Tuple Methods
- count() is a method of the tuple object.
vii) Common Functions Used With Tuples
viii) Packing and Unpacking
- Packing: Putting values into a tuple without parentheses.
- Unpacking: Extracting values back into variables.
C) range (Range)
range type represents an immutable sequence of numbers, commonly used for looping a specific number of times. It is memory-efficient because it doesn't store all the values; it computes them on the fly.4. Mapping Type: dict (Dictionary)
•
A dictionary is a
built-in Python data structure that stores data in Key-Value pairs.
Example:
{'name': 'Alex', 'age': 21, 'courses': ['Math',
'CompSci']}
Characteristics
- Mutable: we can change, add, or remove items after the dictionary is created.
- Indexed by Keys: we can access values using their specific keys, not numeric indexes (0, 1, 2...).
- Unique Keys: A dictionary cannot have duplicate keys. If you assign a value to an existing key, the old value is overwritten.
i) Creating a Dictionary
- Method A: Curly Braces (Most Common):
- Method B: The dict() Constructor
- Note: Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys.
ii) Accessing Data
- There
are two primary ways to retrieve a value.
- We
can Use the key inside square brackets.
Method A: Direct Access [ ]
Method B: The .get() Method
- The get() method
returns the value of the specified key in the dictionary.
Syntax of Dictionary get()
Example:
iii) Valid and Invalid Dictionaries
- Keys of a dictionary must be immutable.
- Immutable objects can't be changed once created. Some immutable objects in Python are integer, tuple and string.
Example:
Note: Dictionary values can be of any data type,
including mutable types like lists.
iv Modifying Dictionaries
- Dictionaries are dynamic; we can easily change their content.
Adding or Updating Items
Example
Removing Items
5. Set Types
A) set (Set)
- Unordered: The items have no defined order. You cannot refer to items by index.
- Unique: No duplicate members are allowed.
- Mutable: we can add or remove elements.
i) Creating Sets
- We can create a set using curly brackets {} or the built-in set() constructor.
ii) Create an Empty Set in Python
- Empty curly braces {} will make an empty dictionary in Python.
- To make a set without any elements, we use the set() function without any argument.
iii) Modifying Sets
- Since sets are unordered, you cannot change an item at a specific index. However, you can add and remove items.
- Since sets are unordered, you cannot change an item at a specific index. However, you can add and remove items.
Add Items to a Set:
- add(): Adds a single element.
- update(): Adds multiple elements (can accept lists, tuples, or other sets).
Removing Items
- remove(x): Removes x. Raises an error if x is not found.
- discard(x): Removes x. Does NOT raise an error if x is missing.
- pop(): Removes and returns a random item (since sets are unordered).
- clear(): Empties the set completely.
B) frozenset (Frozen Set)
frozenset is hashable and can be used as a key in a dictionary.6. Boolean Type: bool
int. There are two boolean constants: True and False. In numeric contexts, True behaves like 1 and False behaves like 0.7. Binary Types
These types are used for handling binary data, such as data read from a file, network sockets, or API responses.
bytes: An immutable sequence of integers in the range of 0 to 255. It is often used for working with binary data.bytearray: A mutable counterpart tobytes. You can modify its contents.memoryview: Allows you to access the internal data of an object that supports the buffer protocol (likebytesorbytearray) without copying it, making it memory-efficient for large data operations.
8. None Type:NoneType
None is a singleton object in Python that represents the absence of a value. It is often used as a placeholder for optional parameters or to signify that a variable has no value. Functions that do not explicitly return a value will return None.
Comments
Post a Comment