Table of Contents
ToggleIn Python, data types are used to define the type of a variable. They determine what kind of data a variable can store and what operations can be performed on it. Python is dynamically typed, meaning the data type of a variable is determined at runtime based on the assigned value. In this guide, we’ll explore the various built-in data types in Python, including numeric, string, sequence, dictionary, set, boolean, and none.
Python supports three numeric data types: int, float, and complex.
# Integer
a = 10
print("Type of a:", type(a))
# Float
b = 20.5
print("Type of b:", type(b))
# Complex
c = 3 + 4j
print("Type of c:", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Strings are sequences of characters enclosed in quotes. They are immutable in Python.
# String
s = "Hello, World!"
print("Type of s:", type(s))
print("First character:", s[0])
print("Substring:", s[7:12])
Output:
Type of s: <class 'str'>
First character: H
Substring: World
Sequences include list, tuple, and range. Lists are mutable, tuples and ranges are immutable.
# List
my_list = [1, 2, 3, 4, 5]
print("Type of my_list:", type(my_list))
# Tuple
my_tuple = (1, 2, 3, 4, 5)
print("Type of my_tuple:", type(my_tuple))
# Range
my_range = range(5)
print("Type of my_range:", type(my_range))
Output:
Type of my_list: <class 'list'>
Type of my_tuple: <class 'tuple'>
Type of my_range: <class 'range'>
Dictionaries are collections of key-value pairs. They are mutable and unordered.
# Dictionary
my_dict = {'name': 'John', 'age': 30}
print("Type of my_dict:", type(my_dict))
print("Name:", my_dict['name'])
print("Age:", my_dict['age'])
Output:
Type of my_dict: <class 'dict'>
Name: John
Age: 30
Sets are unordered collections of unique elements. They automatically remove duplicates.
# Set
my_set = {1, 2, 3, 4, 5}
print("Type of my_set:", type(my_set))
print("Set:", my_set)
Output:
Type of my_set: <class 'set'>
Set: {1, 2, 3, 4, 5}
Booleans represent one of two values: True or False.
# Boolean
a = True
b = False
print("Type of a:", type(a))
print("Type of b:", type(b))
Output:
Type of a: <class 'bool'>
Type of b: <class 'bool'>
The None type represents the absence of a value in Python.
# None Type
x = None
print("Type of x:", type(x))
Output:
Type of x: <class 'NoneType'>
Understanding Python data types is essential for writing efficient and effective code. Whether you’re working with numbers, strings, sequences, or more complex data structures, Python provides a wide range of built-in data types to suit your needs. By mastering these data types, you’ll be well-equipped to handle any programming challenge.
Happy coding! 🚀
Python offers multiple built-in data types. Let’s explore Lists, Tuples, Dictionaries, Sets, Booleans, and None with detailed examples and commands you’ll use often in real projects.
A list is an ordered, mutable collection that can hold mixed data types. Lists allow indexing, slicing, and come with many useful methods.
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing items
print(fruits[0]) # First element
print(fruits[-1]) # Last element
# Modifying a list
fruits.append("mango") # Add item
fruits.remove("banana") # Remove item
fruits[1] = "grapes" # Update item
# Slicing
print(fruits[0:2])
# Length of list
print(len(fruits))
Output:
apple
cherry
['apple', 'grapes']
3
A tuple is an immutable ordered collection. Once created, values cannot be changed, but they can be accessed, counted, and indexed.
# Creating a tuple
coordinates = (10, 20, 30, 20)
# Accessing items
print(coordinates[1]) # Second item
# Count and index
print(coordinates.count(20)) # Count occurrence of 20
print(coordinates.index(30)) # Find index of 30
# Tuple unpacking
x, y, z, w = coordinates
print(x, y, z, w)
Output:
20
2
2
10 20 30 20
Dictionaries store data as key-value pairs. They are mutable, fast, and widely used for structured data.
# Creating a dictionary
student = {"name": "Alice", "age": 21, "grade": "A"}
# Accessing values
print(student["name"])
print(student.get("age"))
# Adding and updating
student["city"] = "Dehradun"
student["grade"] = "A+"
# Deleting
del student["age"]
# Looping through dictionary
for key, value in student.items():
print(key, ":", value)
Output:
Alice
21
name : Alice
grade : A+
city : Dehradun
A set is an unordered collection of unique values. Useful for removing duplicates and performing mathematical set operations.
# Creating a set
numbers = {1, 2, 3, 3, 4}
print(numbers) # Duplicates removed
# Adding & removing
numbers.add(5)
numbers.discard(2)
# Set operations
evens = {2, 4, 6}
print(numbers.union(evens)) # Union
print(numbers.intersection(evens)) # Intersection
Output:
{1, 2, 3, 4}
{1, 3, 4, 5, 6, 2}
{4}
Booleans represent True or False. They are often results of comparisons and used in conditions.
# Boolean Example
x = 10
y = 20
print(x > y) # False
print(x < y) # True
print(bool(0)) # False
print(bool("Hi"))# True
Output:
False
True
False
True
None represents the absence of a value. Often used as a placeholder or to signify "nothing".
# None Example
value = None
print(value)
# Checking None
if value is None:
print("Value is empty")
# Functions returning None
def greet():
print("Hello")
result = greet()
print(result)
Output:
None
Value is empty
Hello
None
Lists, Tuples, Dictionaries, Sets, Booleans, and None are the backbone of Python programming. By practicing these extra commands and methods, you will become more efficient in handling real-world programming tasks.
Next up: Python Variables and Type Casting 🔑
