Introduction of Most Common Built in Data Types in Python Programming

Python is a high-level, general-purpose programming language.Python is commonly used for developing websites and software, task automation, data analysis, and data visualizationThere are many built-in data types in Python that are fundamental to any program. Understanding them is essential to write efficient, no-bug code. This blog walks you through the built-in data types commonly used in Python so that you can use them to write your own programs.
Numeric Types

Integers: Integers are counting or ordering numbers that include negative numbers and zero. That is, integers have no fractional or decimal part.
Examples and Usage:
Positive integers: 1, 2, 3, 100
Negative integers: -1, -50, -100
Zero: 0
Operations on Integers:
Addition: 5 + 3 results in 8
Subtraction: 10 – 4 results in 6
Multiplication: 7 * 6 results in 42
Division: 15 / 3 results in 5.0 (returns a float)
Floor Division: 15 // 2 results in 7
Modulus: 15 % two results in 1 (remainder)
Exponentiation: 2 ** 3 results in 8
Floats: Floats are real numbers with a decimal point or exponential (scientific) notation. These numbers have much more decimals than integers, which is useful when you need more precision.
Examples and Usage:
Decimal numbers: 1.23, -0.001, 3.14
Scientific notation: 2e3 (which means 2 * 10^3 or 2000)
Precision and Operations on Floats: Floats can represent a large range of values but are imprecise – they are subject to rounding errors.
Addition: 1.5 + 2.3 results in 3.8
Subtraction: 5.75 – 2.5 results in 3.25
Multiplication: 4.2 * 3.0 results in 12.6
Division: 7.5 / 2.5 results in 3.0
Floor Division: 7.5 // 2 results in 3.0 (returns a float)
Modulus: 7.5 % 2.5 results in 0.0
Exponentiation: 2.0 ** 3.0 results in 8.0
Complex Numbers: A complex number is an ordered pair of a real number, the real part, and an imaginary number, the imaginary part a + bi , where a is the real part and b is the imaginary part.
Examples and Usage:
Complex number: 3 + 4i; 3 is the real part, while 4i is the imaginary part.
Useful in advanced mathematical calculations, such as electrical engineering and physics
Operations on Complex Numbers:
Addition: (1 + 2j) + (3 + 4j) results in (4 + 6j)
Subtraction: (5 + 6j) – (2 + 3j) results in (3 + 3j)
Multiplication: (1 + 2j) * (3 + 4j) results in (-5 + 10j)
Division: (1 + 2j) / (1 + 1j) results in (1.5 + 0.5j)
Sequence Types

Strings: Definition and Thing-ness Strings are sequences of characters delimited by quotation marks of any kind (single’, double ‘”’, or triple quotes ”’ or””) characters. They are recursive, which means that quotation marks must be escaped in order for strings to work properly. Strings are immutable, which one can translate as strings never change.
Creating and Manipulating Strings:
Creating strings: str1 = “Hello, World!”
Accessing characters: str1[0] results in ‘H’
Slicing: str1[1:5] results in ‘ello’
Concatenation: “Hello” + ” ” + “World” results in “Hello World”
Common String Methods:
Split (): Splits the string into a list str1.split(“,”) results in [‘Hello’,’ World!’]
Join (): Takes elements of a list and joins them together into a string with a separator (): join(‘”, [‘Hello’, ‘World’]) = ‘Hello World’
replace(): Replaces a substring with another str1.replace(“World”, “Python”) results in “Hello, Python!”
upper(): Converts to uppercase str1.upper() results in “HELLO, WORLD!”
lower(): Converts to lowercase str1.lower() results in “hello, world!”
Lists: It is a collection of ordered, mutable items of arbitrary data type that is enclosed in square brackets [].
Creating and Manipulating Lists:
Creating a list: list1 = [1, 2, 3, “four”, 5.0]
Accessing elements: list1[0] results in 1
Slicing: list1[1:3] results in [2, 3]
Changing elements: list1[3] = 4 changes the list to [1, 2, 3, 4, 5.0]
Common List Methods
append(6): Stores an item at the end of the list list1.append(6) // [1, 2, 3, 4, 5.0, 6]
remove(): Removes the first occurrence of an item list1.remove(3) becomes [1, 2, 4, 5.0, 6]
sort(): Searches the list and sorts it in ascending order list1.sort() gives you (1, 2, 4, 5.0, 6)
extend(list2): Adds all the items of another list list1.extend([7, 8]) [1, 2, 4, 5.0, 6, 7, 8]
pop(): Removes and returns the last item list1.pop()returns eight, and the list goes to [1, 2, 4, 5.0, 6, 7]
Tuples: Tuples are ordered and unchangeable sequence of items, which can be of diverse data type. The tuples are created by using the method enclosed in parentheses ().
Creating and Accessing Tuples:
Creating a tuple: tuple1 = (1, 2, 3, “four”, 5.0)
Accessing elements: tuple1[0] results in 1
Slicing: tuple1[1:3] results in (2, 3)
Immutable nature and use cases Purpose of tuples. Things can’t change once tuples are created. Also, tuples are faster than lists because they are immutable.
Example Use Cases: Coordinates in a geometric space, database records
Set Types

Sets: Sets are unordered collections of unique items. They are created using curly braces {} or set() function.
Creating and Manipulating Sets:
Creating a set: set1 = {1, 2, 3, 4, 5}
Adding elements: set1.add(6) results in {1, 2, 3, 4, 5, 6}
Removing elements: set1.remove(3) results in {1, 2, 4, 5, 6}
Common Set Methods:
add(): Adds an item to the set
remove(): Removes an item from the set
union(): Returns a new set that has all the elements in both sets set1.union({7, 8}) {1, 2, 4, 5, 6, 7, 8}
intersection(): Returns a new object containing elements that are shared between the two sets set1.intersection({4, 5, 6, 7}) returns {4, 5, 6}
Frozen Sets: Frozen sets are ‘frozen’ versions of sets. You can create them using the function frozenset, and once you’ve created a frozen set, you can’t change it.
Creating and Accessing Frozen Sets:
Creating a frozen set: fset1 = frozenset([1, 2, 3, 4, 5])
Accessing elements: Like sets, elements are accessed through operations, not indexing.
Immutable Nature and Use Cases Frozen sets are helpful in situations where a set needs to be immutable and hashable, such as keys to a dictionary and elements of another set.
Mapping Types

Dictionaries: A Dictionary/Map (or AssociativeArray) is an unordered collection of key-value pairs. Keys are unique, and keys are immutable types (i.e., strings, numbers, tuples). Values can be of any datatype and can be duplicated.
Creating and Accessing Dictionaries:
Creating a dictionary: dict1 = {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘London’}
Accessing values: dict1[‘name’] results in ‘Alice’
A new key-value pair is added to the set: dict1[‘email’] = ‘[email protected]’ The original dictionary: {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘London’} A new key-value pair has been added: {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘London’, ‘email’: ‘[email protected]’}
Replacing the old value: {‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘London’, ‘email’: ‘[email protected]’} dict1[‘age’] = 26 Results in the same dictionary with a new incorrect ‘age’ value.
Common Dictionary Methods

keys(): returns the keys in the form of view object: dict1.keys() returns dict_keys([‘name’, ‘age’, ‘city’, ‘email’])
values(): Returns a view object containing the dictionary’s values dict1.values() returns dict_values([‘Alice’, 26, ‘London’, ‘[email protected]’])
items(): Return a view object that contains the dictionary’s key-value pairs dict1.items() yields dict_items([(‘name’, ‘Alice’), (‘age’, 26), (‘city’, ‘London’), (‘email’, ‘[email protected]’)])
get(): Returns the value associated with a specified key (None if the key is not present), as a side note dict1.get(‘name ‘) returns ‘Alice’.
pop(): Takes a key for an item and returns it and removes the value associated with it: monty.pop(‘age’) returns 26, and now our dictionary is: {‘name’: ‘Monty’, ‘city’: ‘Paris’, ‘email’: ‘[email protected]’}
Boolean Type

Booleans: Booleans can have either of two values: True or False. They are typically used in conditional statements and logical operations.
True and False Values: Boolean values in Python are True and False (note the capitalisation).
All non-zero numbers and all non-empty objects are True, and zero and None and empty objects are False.
Logical Operations
and: Returns True if both operands are True True and False results in False.
or: Is True if True is true for at least one of its operands True True or True is True True True or False is True False True or False is True False False True or False is False False False False False or True is False False True False False True False True or True is also True False True False True True True True There might appear to be redundancy in that truth is detected for True itself. And indeed, you could trivially force it, checking the first operand as True and the following as na.
not: Is true unless the operand is true, and vice versa, not True is false, not False is true.
None Type: NoneType has only one value: None. It is used to represent the absence of a value or a null value. ‘None’ is used as a placeholder for empty variables or function returns.
Usage of None in Python
Initializing Variables: result = None before assigning it an actual value.
Function Defaults: Using None as a default argument in function definitions def func(arg=None)
Checking for NULL: Using if’s to check if a variable is None if the result is None
Comparison with Other Data Types
None is different from False, 0 or the empty string, and is its own type.
None is unlike any other type; it can never be equal (==) to 0, or to “, or to any other meaningful value . None == 0 # returns False None ==” # returns False None ==” # returns False None == AnyOtherThing # returns False . In addition, code may sometimes fail to produce the desired output simply because there was a typographical error (e.g., because of misspelling, extra spaces in unimportant words, or because of faulty capitalisation).
To help handle such scenarios, most programming languages copy your code and then perform a test on the outcome. The most common such operator is called assert. If the assert operator detects a situation that should be impossible – for example: if a variable represents a person’s height in metres but is found to be negative – then it causes the program itself to fail and issues an error message for the programmer.
Using the assert operator looks like this: Height = -1 # Defines ‘Height’ as a variable that represents a person’s height in meters Height > 0 # The line right before the problem: verifies that ‘Height’ is positive assert Height > 0 # The line causing the fault , invokes the assert operator asserts that ‘Height’ is positive Numerous alternative methods and constructs exist for enhancing programmer awareness in dynamic and object-oriented languages.
Type Conversion

Implicit Conversion: Implicit conversion, also known as type coercion, is a process carried out by Python automatically. It’s a process that occurs while in the middle of operations. This is because, during operations, Python might ask for numbers or strings as input, but we give it data of a different type.
When Implicit Conversion Occurs
Integer to Float: When an integer is involved in a floating-point operation, it is converted to a float automatically.
Example: result = 3 + 4.0 results in 7.0
Boolean to Integer: True converts to 1 and False to 0.
Example: result = True + 2 results in 3
Explicit Conversion: Explicit conversion is also called (and sometimes simply referred to as) type casting. Built-in functions are used to force the conversion of a particular data type to another that might or might not be implicitly converted. Sometimes this is required because the compiler does not convert automatically; other times, it is required because more control is needed.
Using Functions like int(), float(), str(), etc.
int(): Converts a value to an integer.
Example: int(‘123’) results in 123
float(): Converts a value to a float.
Example: float(‘123.45’) results in 123.45
str(): Converts a value to a string.
Example: str(123) results in ‘123’
list(): Converts an iterable to a list.
Example: list(‘abc’) results in [‘a’, ‘b’, ‘c’]
tuple(): Converts an iterable to a tuple.
Example: tuple([1, 2, 3]) results in (1, 2, 3)
set(): Converts an iterable to a set.
Example: set([1, 2, 3, 1]) results in {1, 2, 3}
Practical Applications of Data Types

Integers and Floats: Used in financial calculations, scientific computations, and inventory management.
For example, calculate the total price of the items in a shopping cart (using integers as quantity and floats as the price of each item).
Strings: For string data is handling text information, such as for input from users, names of files, or queries into a database.
Example: Storing and manipulating customer names and addresses in a retail application.
Lists and Tuples: these are for ordered collections of items: sequences of data, coordinates, or configurations.
Example: Managing a list of product IDs or a tuple of geographical coordinates.
Dictionaries: For associative arrays or key-value pairs, such as configuration settings or database records.
Example: Storing and retrieving user preferences and settings in a web application.
Sets: Used for collections of unique items, such as tags, categories, and memberships.
Example: Maintaining a set of unique customer email addresses for a newsletter.
Complete our Online Course on Web Development.
Why is it Important to Choose the Right One?

Choosing the right data type: This ensures that the program works fine, it is easy to read, understand and has no errors. Each data type brings specific properties and/or methods to the particular operational group (task).
Memory Efficiency: Some data types, such as lists, require more memory than others (e.g., tuples or sets).
Speed: If you have to do a lot of lookups on your data, it might be faster to use a dictionary than to use a list.
Immutability: Immutable types such as tuples lend themselves to more guaranteed safe use in concurrency and as keys in dictionaries.
Avoiding Common Mistakes with Data Types

Type Mismatch: Ensure that operations are performed on compatible data types to avoid errors.
Example: Avoid adding a string to an integer directly without conversion.
Implicit Conversion Assumptions: Do not assume that implicit conversion will affect your code; explicitly convert datatypes where needed.
Example: Explicitly convert user input to an integer if performing arithmetic operations.
Best Practices for Using Data Types in Python
Use Descriptive Names: Name variables descriptively to indicate their data types and purpose.
Example: user_age instead of x
Consistent Formatting: Follow consistent formatting and style guidelines for readability.
Example: Use camelCase or snake_case consistently.
Validation and Error Handling: Validate inputs and handle errors so your program doesn’t throw type-related runtime errors.
Example: Use try and except blocks to handle conversion errors.
Documentation: Document functions and code blocks to describe the expected data types and behavior.
Example: Use docstrings to explain the function’s input and output data types.
Conclusion
Learn these most common built-in datatypes in Python – integers, floats, strings, lists, tuples, sets, dictionaries, booleans, and None – and write the code more fluently and fluently, and write more effective and robust programs. Python data types should be a huge focus if you want to build robust, clean and flexible applications and solve problems effortlessly.
