Python Data Types

Python is a dynamically typed programming language, which means the type of a variable is inferred at runtime. Python supports a variety of data types that can be used to store and manipulate different kinds of data. In this blog, we will cover the most commonly used Python data types, along with example code snippets.

  1. Numeric types Python supports three numeric types – int, float, and complex.
# Example of numeric types
a = 5           # int
b = 2.5         # float
c = 3 + 4j      # complex

# Arithmetic operations on numeric types
print(a + b)    # 7.5
print(a - b)    # 2.5
print(a * b)    # 12.5
print(a / b)    # 2.0
print(c.real)   # 3.0
print(c.imag)   # 4.0
  1. String type A string is a sequence of characters enclosed in single or double quotes.
# Example of string type
name = 'John'
age = 25
message = f'My name is {name} and I am {age} years old.'

# String operations
print(len(name))             # 4
print(name.upper())         # JOHN
print(name.lower())         # john
print(message.replace('John', 'Jane')) # My name is Jane and I am 25 years old.
  1. Boolean type Boolean data type has only two values – True or False.
# Example of boolean type
is_sunny = True
is_raining = False

# Boolean operations
print(is_sunny and not is_raining)   # True
print(is_sunny or is_raining)        # True
print(not is_sunny)                  # False
  1. List type A list is an ordered collection of elements, enclosed in square brackets.
# Example of list type
fruits = ['apple', 'banana', 'orange']

# List operations
print(len(fruits))              # 3
print(fruits[0])                # apple
print(fruits[-1])               # orange
fruits.append('grape')          # Add element to the end of the list
print(fruits)                   # ['apple', 'banana', 'orange', 'grape']
fruits.pop(1)                   # Remove element at index 1
print(fruits)                   # ['apple', 'orange', 'grape']
  1. Tuple type A tuple is an ordered, immutable collection of elements, enclosed in parentheses.
# Example of tuple type
person = ('John', 25, 'male')

# Tuple operations
print(len(person))              # 3
print(person[0])                # John
print(person[-1])               # male
  1. Set type A set is an unordered collection of unique elements, enclosed in curly braces.
# Example of set type
colors = {'red', 'green', 'blue'}

# Set operations
print(len(colors))              # 3
print('red' in colors)          # True
colors.add('yellow')            # Add element to the set
print(colors)                   # {'red', 'green', 'blue', 'yellow'}
colors.remove('green')          # Remove element from the set
print(colors)                   # {'red', 'blue', 'yellow'}
  1. Dictionary type A dictionary is an unordered collection of key-value pairs, enclosed in curly braces.
# Example of dictionary type
person = {'name': 'John', 'age': 25, 'gender