0% found this document useful (0 votes)
7 views

Data-Types-in-Python-Mutability-Immutability-and-Operations

This document provides an in-depth overview of data types in Python, focusing on mutability, available operations, and conversion methods. It covers numeric types, strings, lists, tuples, sets, and dictionaries, detailing their characteristics, methods, and examples. Understanding these data types is essential for writing efficient and reliable Python code.

Uploaded by

farhanlenova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Data-Types-in-Python-Mutability-Immutability-and-Operations

This document provides an in-depth overview of data types in Python, focusing on mutability, available operations, and conversion methods. It covers numeric types, strings, lists, tuples, sets, and dictionaries, detailing their characteristics, methods, and examples. Understanding these data types is essential for writing efficient and reliable Python code.

Uploaded by

farhanlenova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Data Types in Python: Mutability,

Immutability, and Operations


This document provides a comprehensive overview of data types in Python, focusing on their mutability (whether they can
be changed after creation), available operations, and conversion methods. Understanding data types is fundamental to
writing efficient and reliable Python code. This guide covers numeric types (int, float, complex), strings, and collection types
(lists, tuples, sets, and dictionaries), highlighting key methods and functions for each.

by Farhaaann
Numeric Data Types: int, float, complex
Int Float Complex
The int data type represents integers, The float data type represents The complex data type represents
which are whole numbers without a floating-point numbers, which are complex numbers, which have a real
fractional component. Examples numbers with a decimal point. and an imaginary part. Examples
include 10, -5, and 0. Integers Examples include 3.14, -2.5, and 0.0. include 2 + 3j and -1 - 1j. Complex
support a wide range of arithmetic Floats support arithmetic operations numbers support arithmetic
operations such as addition, similar to integers, as well as operations. The real and imaginary
subtraction, multiplication, division, comparison operations. It's parts can be accessed using the .real
modulo, and exponentiation. important to note that floating-point and .imag attributes, respectively.
Additionally, bitwise operations like arithmetic may introduce small The cmath module provides
AND, OR, XOR, and shifts are also precision errors due to the way these functions for more advanced
supported. numbers are stored in memory. complex number operations.

Arithmetic Operations: +, -, *, /, %, Arithmetic Operations: +, -, *, /, %, Arithmetic Operations: +, -, *, /


** ** Attributes: .real, .imag
Bitwise Operations: &, |, ^, ~, <<, Comparison Operations: ==, !=, <, Cmath Module: cmath.phase(),
>> >, <=, >= cmath.polar(), cmath.rect()
Methods: bit_length(), to_bytes(), Methods: is_integer(), hex(),
from_bytes() fromhex()
String Data Type
A string in Python is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Strings are
immutable, meaning their value cannot be changed after creation. Any operation that appears to modify a string actually
creates a new string.

Escape characters are used to represent special characters within strings:

\n: Newline
\t: Tab
\': Single quote
\": Double quote

\\: Backslash

Python offers several ways to format strings:

% operator (old style): "Value: %s" % "test"


.format() method (versatile): "Value: {}".format("test")
f-strings (concise): value = "test"; f"Value: {value}"

Common string methods include:

len(): Returns the length of the string


lower(): Converts the string to lowercase
upper(): Converts the string to uppercase
strip(): Removes leading and trailing whitespace
replace(): Replaces occurrences of a substring
split(): Splits the string into a list of substrings
join(): Concatenates a list of strings into a single string

find(): Finds the index of a substring


count(): Counts the occurrences of a substring

The re module provides regular expression operations for advanced pattern matching and manipulation:

re.search(): Searches for a pattern in a string


re.match(): Matches a pattern at the beginning of a string
re.findall(): Finds all occurrences of a pattern
re.sub(): Replaces occurrences of a pattern
List Data Type
A list is an ordered, mutable sequence of items. Lists are defined using square brackets [] and can contain items of
different data types. Lists support indexing and slicing for accessing and extracting elements.

Built-in list functions:

len(): Returns the number of items in the list


max(): Returns the largest item in the list
min(): Returns the smallest item in the list
sum(): Returns the sum of all items in the list (numeric items only)

Common list methods:

append(): Adds an item to the end of the list


extend(): Appends multiple items from another iterable to the end of the list

insert(): Inserts an item at a specific index


remove(): Removes the first occurrence of an item
pop(): Removes and returns the item at a specific index
index(): Returns the index of the first occurrence of an item
count(): Returns the number of occurrences of an item
sort(): Sorts the list in place
reverse(): Reverses the list in place
clear(): Removes all items from the list
copy(): Returns a shallow copy of the list

List comprehensions provide a concise way to create lists:

Example: [x**2 for x in range(10)] creates a list of squares from 0 to 9.


Tuple Data Type
A tuple is an ordered, immutable sequence of items. Tuples are defined using parentheses (). Once a tuple is created, its
contents cannot be modified. Tuples support indexing and slicing, similar to lists.

Built-in tuple functions:

len(): Returns the number of items in the tuple


max(): Returns the largest item in the tuple
min(): Returns the smallest item in the tuple
sum(): Returns the sum of all items in the tuple (numeric items only)

Common tuple methods:

count(): Returns the number of occurrences of an item


index(): Returns the index of the first occurrence of an item

Tuple packing and unpacking allows for convenient creation and assignment of tuples:

Example:

# Packing
my_tuple = 1, 2, "hello"

# Unpacking
a, b, c = my_tuple
Set Data Type
A set is an unordered collection of unique items. Sets are defined using curly braces {} or the set() constructor. Sets are
mutable, allowing you to add or remove elements, but they cannot contain duplicate values.

Set operations:

union: Combines two sets


intersection: Returns common elements between two sets
difference: Returns elements present in the first set but not in the second
symmetric difference: Returns elements present in either set, but not in both

Built-in set functions:

len(): Returns the number of items in the set


max(): Returns the largest item in the set
min(): Returns the smallest item in the set
sum(): Returns the sum of all items in the set (numeric items only)

Common set methods:

add(): Adds an item to the set


remove(): Removes an item from the set (raises an error if the item is not found)
discard(): Removes an item from the set (does nothing if the item is not found)
pop(): Removes and returns an arbitrary item from the set
clear(): Removes all items from the set
copy(): Returns a shallow copy of the set
update(): Adds items from another iterable to the set
intersection_update(): Updates the set with the intersection of itself and another iterable
difference_update(): Updates the set with the difference of itself and another iterable
symmetric_difference_update(): Updates the set with the symmetric difference of itself and another iterable

Set comprehensions provide a concise way to create sets:

Example: {x for x in range(10) if x % 2 == 0} creates a set of even numbers from 0 to 9.


Dictionary Data Type
A dictionary is an unordered collection of key-value pairs. Dictionaries are defined using curly braces {}. Each key in a
dictionary must be unique and immutable (e.g., string, number, tuple), while values can be of any data type. Dictionaries are
mutable, allowing you to add, remove, or update key-value pairs.

Built-in dictionary functions:

len(): Returns the number of key-value pairs in the dictionary

str(): Returns a string representation of the dictionary

Common dictionary methods:

get(): Returns the value associated with a key (returns None if the key is not found)
keys(): Returns a view object containing the keys in the dictionary
values(): Returns a view object containing the values in the dictionary
items(): Returns a view object containing the key-value pairs in the dictionary as tuples
pop(): Removes and returns the value associated with a key
popitem(): Removes and returns an arbitrary key-value pair
clear(): Removes all key-value pairs from the dictionary
copy(): Returns a shallow copy of the dictionary
update(): Updates the dictionary with key-value pairs from another dictionary or iterable
fromkeys(): Creates a new dictionary with the specified keys and a default value

setdefault(): Returns the value associated with a key (inserts the key with a default value if it is not found)

Dictionary comprehensions provide a concise way to create dictionaries:

Example: {x: x**2 for x in range(5)} creates a dictionary where keys are numbers from 0 to 4 and values are their squares.
Mutable vs. Immutable Objects and Data Type
Conversion
Mutable objects can be changed after creation. Examples include lists, sets, and dictionaries. Mutability can lead to side
effects and unexpected behavior if not handled carefully. For example, modifying a list in place will affect all references to
that list.

Immutable objects cannot be changed after creation. Examples include integers, floats, strings, and tuples. Immutability
offers benefits such as predictable behavior and thread safety, as the value of an immutable object is guaranteed not to
change.

Data type conversion allows you to change the type of an object:

Implicit type conversion: Occurs automatically in certain situations (e.g., adding an integer to a float)
Explicit type conversion: Uses conversion functions to change the type of an object

Conversion functions:

int(): Converts to an integer


float(): Converts to a floating-point number
str(): Converts to a string
list(): Converts to a list
tuple(): Converts to a tuple
set(): Converts to a set
dict(): Converts to a dictionary

Example: Converting a string to an integer: int("123")

Example: Converting a list to a tuple: tuple([1, 2, 3])

You might also like