Home » Python Type Casting Tutorial with Examples

Python Type Casting Tutorial with Examples

Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription

Type casting is the process of converting one data type to another in Python. This is particularly useful when you want to perform operations between different types, such as converting user input (which is always a string) to an integer or float for mathematical calculations.

In Python, type casting can be done using built-in functions like int(), float(), str(), list(), tuple(), and many more.

In this tutorial, you'll learn:

What is type casting?
Implicit vs. explicit type casting
Type casting between common data types
Type casting with lists, tuples, and sets
Practical examples of type casting

1. What is Type Casting?

Type casting refers to the process of converting a variable from one data type to another. Python is a dynamically-typed language, meaning that variable types are determined at runtime and can change. This flexibility allows for both implicit and explicit type casting.

Implicit type casting: The Python interpreter automatically converts one type to another.
Explicit type casting: The programmer manually converts one type to another using built-in functions.

2. Implicit vs. Explicit Type Casting

Implicit Type Casting

In implicit type casting, Python automatically converts one data type to another when it can do so safely. For example, Python can automatically convert an integer to a float during arithmetic operations because no precision is lost.

Example 1: Implicit Type Casting

# Implicit conversion from int to float
num_int = 5
num_float = 2.5

# Adding int and float, Python automatically converts int to float
result = num_int + num_float
print(result)  # Output: 7.5
print(type(result))  # Output: <class 'float'>

In this example:

num_int (an integer) is implicitly converted to a float during the addition operation because the other operand (num_float) is a float.
The result is a float, and no explicit casting is needed.

Explicit Type Casting

In explicit type casting, you manually convert one type to another using built-in functions like int(), float(), and str().

Example 2: Explicit Type Casting

# Explicit type casting
num_str = "10"
num_int = int(num_str)  # Convert string to integer

# Now we can add it to an integer
result = num_int + 5
print(result)  # Output: 15
print(type(result))  # Output: <class 'int'>

In this example:

num_str is a string representing the number “10”.
We explicitly cast it to an integer using int(), allowing us to perform arithmetic with it.

3. Type Casting Between Common Data Types

Python provides several built-in functions to cast between various data types. Here’s how to convert between the most commonly used types.

3.1. Converting to Integer (int())

You can convert a string or float to an integer using the int() function. If you try to convert a string that doesn't represent a number, Python will raise a ValueError.

# Converting float to int (truncates the decimal part)
num_float = 9.81
num_int = int(num_float)
print(num_int)  # Output: 9

# Converting string to int
num_str = "25"
num_int = int(num_str)
print(num_int)  # Output: 25

# Invalid conversion (raises ValueError)
# invalid_str = "Hello"
# int(invalid_str)  # Raises ValueError: invalid literal for int()

Note: Converting a float to an integer truncates the decimal part (it doesn't round the value).

3.2. Converting to Float (float())

The float() function converts integers or strings representing numbers into floating-point numbers.

# Converting int to float
num_int = 10
num_float = float(num_int)
print(num_float)  # Output: 10.0

# Converting string to float
num_str = "15.75"
num_float = float(num_str)
print(num_float)  # Output: 15.75

3.3. Converting to String (str())

The str() function converts other data types (like integers, floats, and lists) to strings.

# Converting int to string
num_int = 100
num_str = str(num_int)
print(num_str)  # Output: '100'
print(type(num_str))  # Output: <class 'str'>

# Converting float to string
num_float = 12.34
num_str = str(num_float)
print(num_str)  # Output: '12.34'

4. Type Casting with Lists, Tuples, and Sets

Python also allows type casting between iterable data types like lists, tuples, and sets.

4.1. Converting to List (list())

You can convert other iterable types (like strings, tuples, and sets) into lists using the list() function.

# Converting tuple to list
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)  # Output: [1, 2, 3]

# Converting string to list (splits into characters)
my_str = "Hello"
my_list = list(my_str)
print(my_list)  # Output: ['H', 'e', 'l', 'l', 'o']

4.2. Converting to Tuple (tuple())

Similarly, you can convert other iterable types into tuples using the tuple() function.

# Converting list to tuple
my_list = [4, 5, 6]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (4, 5, 6)

# Converting string to tuple
my_str = "World"
my_tuple = tuple(my_str)
print(my_tuple)  # Output: ('W', 'o', 'r', 'l', 'd')

4.3. Converting to Set (set())

You can convert iterable types like lists or tuples to sets using the set() function. Sets automatically remove duplicate elements.

# Converting list to set
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)
print(my_set)  # Output: {1, 2, 3}

# Converting string to set (removes duplicate characters)
my_str = "hello"
my_set = set(my_str)
print(my_set)  # Output: {'h', 'e', 'l', 'o'}

5. Practical Examples of Type Casting

Example 1: Taking User Input and Converting Types

When you take user input, Python treats everything as a string. You often need to cast the input to the correct type before performing any operations.

# Taking user input as string
age_str = input("Enter your age: ")

# Casting the input to an integer
age = int(age_str)

# Perform arithmetic operation
years_left = 65 - age
print(f"You have {years_left} years left until retirement.")

Output (assuming user input is 30):

You have 35 years left until retirement.

In this example, input() returns a string, so we explicitly cast it to an integer using int() to perform the arithmetic calculation.

Example 2: Converting a List of Strings to Integers

Suppose you have a list of strings representing numbers, and you need to convert them to integers for further processing.

# List of strings
str_list = ["1", "2", "3", "4"]

# Convert each string to an integer using list comprehension
int_list = [int(i) for i in str_list]

print(int_list)  # Output: [1, 2, 3, 4]

Example 3: Converting Between Data Types for File Operations

When working with files, you often need to convert data to the correct type before writing or reading from the file.

# Writing integers to a file as strings
with open("numbers.txt", "w") as file:
    for i in range(5):
        file.write(str(i) + "\n")  # Convert int to str before writing

# Reading from a file and converting back to integers
with open("numbers.txt", "r") as file:
    lines = file.readlines()
    numbers = [int(line.strip()) for line in lines]

print(numbers)  # Output: [0, 1, 2, 3, 4]

In this example:

We convert integers to strings using str() before writing them to a file.
When reading the numbers back from the file, we cast the strings back to integers using int().

Example 4: Calculating Average from Mixed Data Types

Suppose you have a list that contains both integers and floats, and you want to calculate the average value.

data = [10, 12.5, 8, 9.75, 11]

# Convert all elements to float before calculating the average
average = sum(float(i) for i in data) / len(data)
print(f"Average: {average}")

Output:

Average: 10.25

Conclusion

Type casting is a fundamental feature in Python that allows you to convert data from one type to another. Here’s a summary of what you’ve learned:

Implicit type casting is done automatically by Python when safe to do so.
Explicit type casting is manually performed using built-in functions like int(), float(), str(), list(), and set().
Type casting between common data types such as integers, floats, strings, lists, tuples, and sets is crucial for handling user input, file I/O, and many other tasks.

Proper use of type casting ensures that your program operates on the correct data types and prevents runtime errors.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More