Digging into Python: Data Types
Python is a dynamically typed language, which means that the data type of a variable is determined at runtime based on the value it holds.
Python provides a number of built-in data types, each with its own set of operations and methods.
Here's an overview of some of the most used data types in Python:
Numeric:
- Integers (int): Integers are whole numbers without decimal points. They can be positive or negative, and there is no limit to their size.
- Floats (float): Floats are numbers with decimal points. They can also be positive or negative, and there is no limit to their precision.
# int | |
number1 = 1 | |
print(number1, 'is of type', type(number1)) | |
# float | |
number2 = 3.5 | |
print(number2, 'is of type', type(number2)) | |
# complex | |
number3 = 5+7j | |
print(number3, 'is of type', type(number3)) |
- Strings (str): Strings are sequences of characters enclosed in quotation marks (either single or double). They can be indexed and sliced like lists, and there are a number of built-in methods for working with strings.
# String | |
message = 'Keep on coding' | |
# Print String value | |
print(message) |
- bool: holds either True or False
# bool | |
A = true | |
# Print Boolean value | |
print(type(A)) |
- Lists (list): Lists are ordered sequences of elements, which can be of any data type. They are mutable, meaning that you can add, remove, or modify elements in place.
- Tuples (tuple): Tuples are similar to lists, but are immutable, meaning that their elements cannot be changed once they are created.
# List | |
fruits = ["Apple", "Banana", "Lemon"] | |
# access element at index 1 in List | |
print(fruits[1]) # Banana | |
# Tuple | |
values = ('Python', 'Tuple', 1) | |
# access element at index 0 in Tuple | |
print(values[0]) # Python |
- Dictionaries (dict): Dictionaries are unordered collections of key-value pairs. The keys are typically strings or integers, and the values can be of any data type. Dictionaries are mutable and can be modified in place.
# create a dictionary named months | |
months = {1: 'January', 2: 'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', | |
10:'October', 11:'November', 12:'December'} | |
# print dictionary | |
print(months) |
- Sets (set): Sets are unordered collections of unique elements. They are mutable and can be modified in place.
# create a set named person_id | |
person_id = {1, 2, 3, 4, 5} | |
# display person_id elements | |
print(person_id) | |
# display type of person_id | |
print(type(person_id)) |
In addition to these built-in data types, Python also provides a number of other specialized data types, such as byte arrays, ranges, and complex numbers.
Understanding Python's data types is essential. By choosing the right data type for a given task, you can ensure that your code is easy to read, maintain, and scale.
Comments
Post a Comment