Built-in Data Type of Python Programming
Many built-in data types in Python Programming are fundamental to any program. Understanding them is essential to writing efficient, no-bug code. This blog walks you through the built-in data types commonly used in Python Programming so that you can use them to write your programs.
Numeric Types
Integers
Integers are counting or ordering numbers that include negative numbers and zeros. 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
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. Such as a + bj, 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
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 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 sequences 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 Programming are True and False (note the capitalization).
All non-zero numbers and all non-empty objects are True, and zero and None and empty objects are False.
Logical Operations
- and: The “and” operation takes two Boolean inputs and returns a single Boolean output.
It is true only if both inputs are true.
The operation is typically represented with a truth table, which shows the output for all possible combinations of the inputs:
- or: “or” is a fundamental operation in logic and computer science. It operates on two Boolean values and returns true if at least one of the operands is true. If both operands are false, it returns false.
Here is a more detailed breakdown:
- Operands: The “or” operation works with two inputs, typically referred to as operands.
- Output: The result is a single Boolean value (true or false).
The truth table for the “or” operation is as follows:
3. not: the “not” operation, also known as negation, is a unary operation that takes a single Boolean input and inverts its value. The “not” operation changes true to false and false to true.
Truth Table for “not” Operation:
NoneType
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 Programming
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
In Python programming, None represents the absence of a value or a null reference. Let’s compare None with other common data types:
Comparison with Boolean
None vs True/False:
None is often used to signify “no value” or “unknown.”
In a boolean context, None is considered False.
Comparison with Numeric Types
None vs Integer/Float:
None is not an integer or a float. It cannot be used in arithmetic operations.
Operations like addition, subtraction, etc., with None will raise a TypeError.
Comparison with Strings
None vs String:
None is not a string and cannot be concatenated with strings directly.
Trying to concatenate None with a string will result in a TypeError.
Comparison with Collections (Lists, Tuples, Sets, Dictionaries)
None vs Collections:
None can be an element of a collection but is not itself a collection.
An empty collection (e.g., [], (), {}, set()) is not the same as None.
Type Conversion
Implicit Conversion
Implicit conversion, also known as type coercion, is a process carried out by Python Programming automatically.
It’s a process that occurs while in the middle of operations. This is because, during operations, Python Programming 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
Real-world Examples of Using Different Data Types
Integers and Floats: Used in financial calculations, scientific computations, and inventory management.
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: that is, for 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.
Data Type – Why is it Important to Choose the Right One?
Choosing the right data type 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).
Efficiency and Performance Considerations
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.
Common Pitfalls and Best Practices
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 Programming
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 behaviour.
Example: Use docstrings to explain the function’s input and output data types.
Conclusion
Learn these most common built-in datatypes in Python Programming – integers, floats, strings, lists, tuples, sets, dictionaries, booleans, and None – and write the code more 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.