Python Casting Guide: Convert Numbers, Strings & Lists

目次

1. Introduction

Python is a programming language with simple syntax and powerful features, widely used by everyone from beginners to advanced users. Among its features, “casting (type conversion)” is one of the essential techniques for handling data correctly. In this article, we’ll explain Python’s casting (type conversion) in detail, using code examples to make it easy for beginners to understand. By reading this article, you’ll learn the following:
  • Basic concepts of casting (type conversion) in Python
  • Differences between explicit and implicit type conversion
  • Specific methods and considerations for type conversion
  • Common errors and how to avoid them
Understanding casting makes data handling more flexible and helps prevent bugs. In particular, when working with different data types, performing the appropriate type conversion is crucial.

2. What Is Casting (Type Conversion)? 【Python Basics】

2.1 Definition of Casting (Type Conversion)

Casting (type conversion) refers to converting a data type to another data type. For example, you can convert an integer to a string or a string to a numeric value. Casting is needed in cases such as:
  • When you want to convert user input (usually a string) to a number for calculations
  • When you want to convert a list of numbers to a string to format it
  • To handle different data types properly in Python’s internal processing
In Python, you can easily perform type conversion using built‑in functions.

2.2 Explicit Type Conversion (Explicit Type Conversion)

Explicit type conversion means that the developer intentionally converts one data type to another. In Python, you perform explicit type conversion with functions such as the following.
Conversion FunctionDescriptionExample
int()Convert strings or floating‑point numbers to integersint("10")10
float()Convert strings or integers to floating‑point numbersfloat("3.14")3.14
str()Convert numbers, lists, etc. to stringsstr(100)"100"
list()Convert tuples or strings to listslist("abc")['a', 'b', 'c']
tuple()Convert lists to tuplestuple([1, 2, 3])(1, 2, 3)
dict()Convert key‑value pairs to dictionariesdict([(1, 'a'), (2, 'b')]){1: 'a', 2: 'b'}

Example: Explicit Type Conversion

# Convert integer to string
num = 10
str_num = str(num)
print(str_num)  # "10"
print(type(str_num))  # <class 'str'>

# Convert string to floating‑point number
float_num = float("3.14")
print(float_num)  # 3.14
print(type(float_num))  # <class 'float'>

2.3 Implicit Type Conversion (Implicit Type Conversion)

Implicit type conversion means that Python automatically converts data types. Even without explicit instructions from the developer, Python adjusts types internally as needed.

Example: Implicit Type Conversion

num_int = 10  # integer type
num_float = 2.5  # floating‑point number

# integer + float → converted to float
result = num_int + num_float
print(result)  # 12.5
print(type(result))  # <class 'float'>
In this way, Python automatically adjusts data types so that operations produce correct results.

2.4 Benefits and Cautions of Using Casting

Benefits of Casting

  • You can properly handle user input and other data
  • Calculations and operations across different data types become possible
  • Explicit casting makes program behavior easier to predict

⚠️ Cautions When Casting

  • Improper type conversion can cause errors Example: int("abc") cannot be converted and raises a ValueError
  • Relying too much on implicit conversion can lead to bugs Example: Concatenating an integer and a string directly raises a TypeError
  • Type conversion has a performance cost Converting large amounts of data can affect performance

Next Section

RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

3. Python Data Types and Conversion

3.1 Major Data Types in Python

Python has the following basic data types.
Data TypeDescriptionExample
int (integer)Data type representing integers10, -5, 1000
float (floating-point number)Numeric values that include decimals3.14, -2.5, 1.0
str (string)Sequence of characters (text)"Hello", 'Python'
bool (boolean)Type that holds True or FalseTrue, False
list (list)Array type that holds multiple values[1, 2, 3], ['a', 'b', 'c']
tuple (tuple)Immutable list(1, 2, 3), ('x', 'y')
dict (dictionary)Data type that holds key-value pairs{'name': 'Alice', 'age': 25}
set (set)Collection that does not allow duplicates{1, 2, 3}, {'apple', 'banana'}

3.2 Conversions Between Data Types

3.2.1 Conversion to Numeric Types (int, float)

num_str = "100"
num_int = int(num_str)  # Convert string "100" to integer 100
num_float = float(num_int)  # Convert integer 100 to floating-point number 100.0

print(num_int, type(num_int))  # 100 <class 'int'>
print(num_float, type(num_float))  # 100.0 <class 'float'>

3.2.2 Conversion to String (str)

num = 42
str_num = str(num)  # Convert integer 42 to string "42"
print(str_num, type(str_num))  # "42" <class 'str'>

3.2.3 Conversion to List, Tuple, and Set

tuple_data = (1, 2, 3)
list_data = list(tuple_data)  # Convert tuple to list
print(list_data, type(list_data))  # [1, 2, 3] <class 'list'>

list_data = [4, 5, 6]
tuple_data = tuple(list_data)  # Convert list to tuple
print(tuple_data, type(tuple_data))  # (4, 5, 6) <class 'tuple'>

3.2.4 Conversion to Dictionary

list_of_pairs = [[1, 'apple'], [2, 'banana']]
dict_data = dict(list_of_pairs)  # Convert list to dictionary
print(dict_data, type(dict_data))  # {1: 'apple', 2: 'banana'} <class 'dict'>

3.3 Summary of Data Type Conversions

In Python, you can convert various data types using built-in functions such as int(), float(), str(), etc.
Conversion FunctionDescriptionExample
int(x)Convert to integerint("100")100
float(x)Convert to floating-point numberfloat("3.14")3.14
str(x)Convert to stringstr(42)"42"
list(x)Convert to listlist((1, 2, 3))[1, 2, 3]
tuple(x)Convert to tupletuple([1, 2, 3])(1, 2, 3)
set(x)Convert to setset([1, 2, 2, 3]){1, 2, 3}
dict(x)Convert to dictionarydict([(1, 'a'), (2, 'b')]){1: 'a', 2: 'b'}

4. How to Perform Explicit Type Conversion (Casting) with Code Examples

In Python, you can perform an Explicit Type Conversion to deliberately change a data type. This is a method where developers manually convert data types using built-in functions like int() or str().

4.1 Converting to Integer (int)

# Convert string to integer
num1 = int("10")
print(num1, type(num1))  # 10 <class 'int'>

# Convert floating-point number to integer (truncating the decimal part)
num2 = int(3.99)
print(num2)  # 3

# Convert boolean to integer
num3 = int(True)
num4 = int(False)
print(num3, num4)  # 1 0

4.2 Converting to Floating-Point Number (float)

# Convert string to floating-point number
num1 = float("10.5")
print(num1, type(num1))  # 10.5 <class 'float'>

# Convert integer to floating-point number
num2 = float(10)
print(num2)  # 10.0

4.3 Converting to String (str)

# Convert number to string
num1 = str(100)
num2 = str(3.14)
print(num1, type(num1))  # "100" <class 'str'>
print(num2, type(num2))  # "3.14" <class 'str'>

4.4 Converting to List (list)

# Convert tuple to list
tuple_data = (1, 2, 3)
list_data = list(tuple_data)
print(list_data, type(list_data))  # [1, 2, 3] <class 'list'>

# Convert string to list
str_data = "hello"
list_chars = list(str_data)
print(list_chars)  # ['h', 'e', 'l', 'l', 'o']

4.5 Converting to Tuple (tuple)

# Convert list to tuple
list_data = [1, 2, 3]
tuple_data = tuple(list_data)
print(tuple_data, type(tuple_data))  # (1, 2, 3) <class 'tuple'>

4.6 Converting to Set (set)

# Convert list to set (remove duplicates)
list_data = [1, 2, 2, 3, 3, 3]
set_data = set(list_data)
print(set_data, type(set_data))  # {1, 2, 3} <class 'set'>

4.7 Converting to Dictionary (dict)

# Convert list of lists to dictionary
list_of_pairs = [[1, 'apple'], [2, 'banana']]
dict_data = dict(list_of_pairs)
print(dict_data)  # {1: 'apple', 2: 'banana'}

4.8 Summary

Explicit type conversion in Python is important for making programs more flexible. By using int(), float(), str(), etc., appropriately, converting between different data types becomes easy.
Conversion FunctionDescription
int(x)Convert to integer
float(x)Convert to floating-point number
str(x)Convert to string
list(x)Convert to list
tuple(x)Convert to tuple
set(x)Convert to set
dict(x)Convert to dictionary
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. Implicit Type Conversion (Python’s Automatic Conversion)

5.1 What is the type conversion that Python performs automatically?

Implicit type conversion is a mechanism where Python automatically converts to the appropriate data type without the developer explicitly specifying it. Python’s implicit type conversion mainly occurs during operations on numeric types (int, float, complex).

Example: Operations between integers (int) and floating-point numbers (float)

num_int = 10   # integer
num_float = 2.5  # floating-point number

result = num_int + num_float  # Python implicitly converts int to float
print(result, type(result))  # 12.5 <class 'float'>

5.2 In what situations does implicit conversion occur?

Case 1: Integer (int) → Floating-point (float)

a = 5
b = 2.0
result = a / b  # Python converts int to float
print(result, type(result))  # 2.5 <class 'float'>

Case 2: Integer (int) → Complex (complex)

a = 10   # int
b = 2 + 3j  # complex (imaginary)
result = a + b
print(result, type(result))  # (12+3j) <class 'complex'>

Case 3: Boolean (bool) → Numeric (int, float)

print(True + 2)   # 3  (True is treated as 1)
print(False + 3.5)  # 3.5 (False is treated as 0)

5.3 Precautions and Workarounds for Implicit Type Conversion

⚠️ Caution 1: Mixing strings (str) with numbers (int, float)

num = 10
text = "yen"

# This will cause an error
# print(num + text)  # TypeError

# Correct approach
print(str(num) + text)  # "10 yen"

⚠️ Caution 2: Implicit conversion does not occur for lists or dictionaries

num_list = [1, 2, 3]

# This will cause an error
# print(num_list + 10)  # TypeError

# Correct approach
num_list.append(10)
print(num_list)  # [1, 2, 3, 10]

5.4 Benefits and Drawbacks of Implicit Type Conversion

Benefits
  • Developers can perform calculations smoothly without having to think about type conversion.
  • intfloat or intcomplex, etc., allow conversions that do not compromise data precision.
  • When bool is converted to int, intuitive calculations like True + 1 == 2 become possible.
⚠️ Drawbacks
  • Unintended type conversions can cause bugs (e.g., when an int becomes a float, rounding errors may occur).
  • Data types such as lists and dictionaries are not implicitly converted, so appropriate handling is required.

5.5 Summary

In Python, implicit type conversion occurs primarily with numeric types, allowing calculations to be performed with the appropriate type without the developer explicitly casting.
Source TypeTarget TypeExample
intfloatfloat10 + 2.5 → 12.5
intcomplexcomplex10 + (2+3j) → (12+3j)
boolintintTrue + 1 → 2

6. Common Errors and Countermeasures in Python Casting

6.1 Main Errors that Occur During Casting

The following errors commonly occur when casting (type conversion) in Python.
Error TypeCauseExample
ValueErrorWhen attempting to cast data that cannot be convertedint("abc")
TypeErrorWhen trying to operate on incompatible types10 + "5"
KeyErrorWhen specifying a key that does not exist in a dictmy_dict["missing_key"]
AttributeErrorWhen using a method or attribute that does not exist for the type10.append(5)

6.2 ValueError: Converting Invalid Values

# The string "abc" cannot be converted to an integer
num = int("abc")  # ValueError
Solution
user_input = "abc"

if user_input.isdigit():
    num = int(user_input)
    print(num)
else:
    print("Cannot convert to a number")

6.3 TypeError: Improper Operations Between Types

num = 10
text = "yen"
print(num + text)  # TypeError
Solution
print(str(num) + text)  # "10 yen"

6.4 KeyError: Retrieving a Nonexistent Key from a Dictionary

my_dict = {"name": "Alice", "age": 25}
print(my_dict["gender"])  # KeyError
Solution
print(my_dict.get("gender", "No"))  # "No information"

6.5 AttributeError: Using a Nonexistent Method or Attribute

num = 10
num.append(5)  # AttributeError
Solution
if hasattr(num, "append"):
    num.append(5)
else:
    print("This object does not have an append() method")

6.6 ZeroDivisionError: Division by Zero Error

result = 10 / 0  # ZeroDivisionError
Solution
num = 10
denominator = 0

if denominator != 0:
    result = num / denominator
    print(result)
else:
    print("Division by zero is not allowed")

6.7 IndexError: List Index Out of Range

my_list = [1, 2, 3]
print(my_list[5])  # IndexError
Solution
if 0 <= index < len(my_list):
    print(my_list[index])
else:
    print("The specified index is out of range")

6.8 TypeError: Incorrect Argument Types for a Function

def add_numbers(a: int, b: int):
    return a + b

print(add_numbers(10, "20"))  # TypeError
Solution
def add_numbers(a, b):
    if isinstance(a, (int, float)) and isinstance(b, (int, float)):
        return a + b
    else:
        return "Please enter a numeric value"

print(add_numbers(10, "20"))  # "Please enter a numeric value"

6.9 Summary

In Python casting (type conversion), the following errors are common, so it is important to take appropriate measures.
ErrorCauseMitigation
ValueErrorConverting invalid valuesCheck with isdigit()
TypeErrorImproper operations between typesExplicitly convert with str()
KeyErrorReferencing a nonexistent dictionary keyUse dict.get()
AttributeErrorCalling a nonexistent methodCheck with hasattr()
ZeroDivisionErrorDivision by zeroAvoid with denominator != 0
IndexErrorList index out of rangeCheck with if index < len(list)

7. Practical: Using Casts in Python | With Code Examples

7.1 Converting User Input to Numbers for Calculation

age = input("Please enter your age: ")  # User input is of type str
if age.isdigit():  # Check if it's numeric
    age = int(age)  # Convert to integer
    print(f"In 10 years, you will be {age + 10} years old.")
else:
    print("Please enter a numeric value.")

7.2 Converting List Numbers to Strings and Joining

numbers = [10, 20, 30, 40]
str_numbers = [str(num) for num in numbers]  # Convert each element to a string
result = ", ".join(str_numbers)
print(result)  # "10, 20, 30, 40"

7.3 Casting When Processing CSV Data

csv_data = [
    ["Alice", "25", "170.5"],
    ["Bob", "30", "180.2"],
]

for row in csv_data:
    name = row[0]
    age = int(row[1])  # Convert age to integer
    height = float(row[2])  # Convert height to float
    print(f"{name} is {age} years old, and their height is {height} cm.")

7.4 Casting JSON Data

import json

json_str = '{"name": "Alice", "age": "25", "height": "170.5"}'
data = json.loads(json_str)

data["age"] = int(data["age"])
data["height"] = float(data["height"])

print(data)  # {'name': 'Alice', 'age': 25, 'height': 170.5}

7.5 Treating Dictionary Keys as Numbers

data = {"1": "apple", "2": "banana", "3": "cherry"}

new_data = {int(k): v for k, v in data.items()}
print(new_data)  # {1: 'apple', 2: 'banana', 3: 'cherry'}

7.6 Rounding Calculation Results to Integers

num = 3.75

# Round to nearest integer
rounded_num = round(num)
print(rounded_num)  # 4

# Truncate
truncated_num = int(num)
print(truncated_num)  # 3

7.7 Treating Boolean Values as Numbers

print(int(True))  # 1
print(int(False))  # 0

7.8 Summary

Using casts in Python appropriately makes data processing smoother. In particular, casts are important in the following cases.
Use CaseCasting Method
User Input Processingint() and float()
Converting List Data to Strings[str(x) for x in list]
Type Conversion for CSV and JSON Dataint(), float()
Converting Dictionary Keys to Numbers{int(k): v for k, v in dict.items()}
Rounding Calculation Results to Integersround() and int()
Using Boolean Values as Numbersint(True) → 1, int(False) → 0

8. Frequently Asked Questions and Solutions About Python Casting [FAQ]

8.1 Are casting and type conversion the same?

Yes, basically casting (cast) and type conversion (type conversion) have the same meaning. However, the term “cast” often refers specifically to “explicit type conversion”.

8.2 Is casting possible between all data types?

No, casting is not possible between all data types. Let’s look at examples of cases where type conversion is possible and where it is not.

✔ Castable examples

print(int("10"))  # 10
print(float("3.14"))  # 3.14
print(str(100))  # "100"
print(list("abc"))  # ['a', 'b', 'c']

❌ Uncastable examples (raise errors)

print(int("abc"))  # ValueError
print(float("hello"))  # ValueError
print(int([1, 2, 3]))  # TypeError

8.3 Should implicit type conversion be avoided?

No, Python’s implicit type conversion is very handy when used appropriately, but unintended conversions can cause bugs.
num_int = 10
num_float = 2.5
result = num_int + num_float  # int + float → converted to float
print(result, type(result))  # 12.5 <class 'float'>

8.4 What errors occur when type conversion is mistaken?

Casting failures mainly result in the following three errors.
ErrorCauseExample
ValueErrorInvalid value for type conversionint("abc")
TypeErrorAttempting to operate on incompatible types10 + "5"
AttributeErrorUsing a non-existent method10.append(5)
How to prevent errors
value = "abc"

if value.isdigit():
    num = int(value)
else:
    print("Cannot convert to a number")

8.5 What is the difference between isinstance() and casting?

isinstance() is a function that checks a variable’s type, which is different from casting (type conversion).
num = 10
print(isinstance(num, int))  # True
print(isinstance(num, float))  # False

8.6 How to safely cast user input?

User input is obtained via input(), so it always comes in as a string (str). To prevent errors, use exception handling (try-except) when casting.
while True:
    user_input = input("Please enter an integer: ")

    try:
        num = int(user_input)
        break
    except ValueError:
        print("Invalid input. Please enter an integer.")

print(f"Entered number: {num}")

8.7 Summary

We have explained the frequently asked questions and solutions about Python casting.
QuestionSolution
What is the difference between casting and type conversion?Basically the same meaning, but “cast” often refers to explicit conversion
Is casting possible between all data types?Not always (e.g., int("abc") raises an error)
Should implicit type conversion be avoided?Useful when used properly, but unintended conversions can cause bugs
What is the difference between isinstance() and casting?isinstance() checks type, casting converts type
What is a safe way to convert types?Using try-except prevents errors

9. Summary | Code examples you can try now

9.1 The importance of casting in Python

Casting (type conversion) is a fundamental technique in Python programming for handling data properly. It is mainly used in the following situations. ✅ Maintain data type consistencyEnable calculations between different data typesPrevent errors

9.2 Basics of casting (type conversion) in Python

In Python, you can explicitly convert data types using built-in functions.
Conversion FunctionDescriptionExample
int(x)Convert to integerint("100")100
float(x)Convert to floating-point numberfloat("3.14")3.14
str(x)Convert to stringstr(100)"100"
list(x)Convert to listlist((1, 2, 3))[1, 2, 3]
tuple(x)Convert to tupletuple([1, 2, 3])(1, 2, 3)
set(x)Convert to setset([1, 1, 2]){1, 2}
dict(x)Convert to dictionarydict([(1, 'a'), (2, 'b')]){1: 'a', 2: 'b'}

9.3 Implicit type conversion in Python

# Integer + float → converted to float
result = 10 + 2.5
print(result, type(result))  # 12.5 <class 'float'>

# Treat boolean as integer
print(True + 1)  # 2
print(False + 5)  # 5

9.4 Common errors during casting and how to address them

ErrorCauseSolution
ValueErrorInvalid value conversionUse isdigit() to check for numeric values
TypeErrorInappropriate operation between typesExplicitly convert using str()
KeyErrorReference to a non-existent dictionary keyUse dict.get()
AttributeErrorCalling a non-existent methodCheck with hasattr()
Example of safe casting
user_input = "100a"

try:
    num = int(user_input)  # Convert to number
    print(f"Conversion successful: {num}")
except ValueError:
    print("Invalid input. Please enter a numeric value.")

9.5 Practical code: Leveraging casting in Python

while True:
    user_input = input("Please enter your age (integers only): ")

    if user_input.isdigit():  # Check if input is numeric
        age = int(user_input)
        print(f"In 10 years, the age will be {age + 10} years.")
        break
    else:
        print("Invalid input. Please enter an integer.")

9.6 Best practices for casting

Check data types in advanceImplement error handlingUse appropriate conversion functionsAvoid over-reliance on implicit conversion

9.7 Summary and future learning points

In this article, we covered the following topics. ✔ Basics of casting in PythonExplicit type conversion (int(), float(), str(), etc.)Implicit type conversion (Python’s automatic conversion)Common casting errors and their solutionsPractical examples of using casting To make Python programming more efficient, be sure to write and try the code yourself! 🚀
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール