Python datatype conversion means creating a value in one type from a value in another type. In this tutorial, you will learn how to convert values using Python built-in functions such as int(), float(), complex(), str(), tuple(), list(), set(), frozenset(), dict(), chr(), and bool().

Python datatype conversion: explicit casting and automatic conversion

In Python, some conversions happen automatically when the operation is safe enough. For example, adding an integer and a float gives a float result. This is usually called implicit type conversion.

</>
Copy
number = 10
price = 2.5

result = number + price

print(result)
print(type(result))
12.5
<class 'float'>

When you intentionally call a conversion function such as int("34") or list("hello"), it is explicit type conversion. Explicit conversion is also called type casting in many beginner tutorials.

Python type conversion functions used in this tutorial

Use the following links to jump to the conversion you need.

FunctionTypical useImportant note
int(x)Convert a number or numeric string to an integerDecimal part is truncated, not rounded
float(x)Convert an integer or numeric string to a floating-point numberInvalid numeric strings raise ValueError
complex(real, imag)Create a complex numberThe imaginary part defaults to 0
str(x)Convert an object to its string formUseful before concatenating with other strings
list(x), tuple(x), set(x)Convert iterable values to collection typesA string is iterated character by character
dict(x)Convert key-value pairs to a dictionaryEach item must provide a key and a value
bool(x)Convert a value to True or FalseEmpty values are usually False

Convert values to integer in Python with int()

int(x) converts x to an integer when Python knows how to represent that value as a whole number.

int(x, base) is used when x is a string representation of a number in a specific base. If the base is not specified for a normal numeric string, Python uses base 10.

When a float is converted with int(), Python removes the decimal part. It does not round the number. In Python 3, there is no separate long type for everyday use; int can hold very large integers as long as memory is available.

Following program demonstrates the conversion of float, string and complex numbers to int.

example.py – Python Program

</>
Copy
float_value = 5.2
str_value = "34"
complex_value = 3.14j

float_value_to_int = int(float_value)
str_value_to_int = int(str_value)
str_value_to_int_base_8 = int(str_value,8)
str_value_to_int_base_6 = int(str_value,6)
complex_value_to_int = int(abs(complex_value))

print(float_value_to_int)
print(str_value_to_int)
print(str_value_to_int_base_8)
print(str_value_to_int_base_6)
print(complex_value_to_int)

Output

5
34
28
22
3

Note : By default, if the value could not be accommodated in an integer, the data type is automatically upgraded to long by the python interpreter. If the value is so long that it could not fit in an integer, then we got python interpreter to upgrade it to long without our attention required.

The note above applies to old Python 2 wording. In Python 3, use int for both small and large whole numbers. A complex number cannot be directly passed to int(); the example uses abs() first to convert the magnitude of the complex number.

</>
Copy
print(int(8.99))
print(int("101", 2))
print(int("1f", 16))
8
5
31

Python int() conversion errors to handle

If the string is not a valid integer for the given base, int() raises ValueError. Use try and except when converting user input.

</>
Copy
value = "45.6"

try:
    number = int(value)
    print(number)
except ValueError:
    print("Cannot convert to int")
Cannot convert to int

Convert values to float in Python with float()

float(x) converts x to a floating-point number. It is commonly used when reading decimal values from strings, forms, files, or command-line input.

Following program demonstrates the conversion of int, string and complex numbers to float.

example.py – Python Program

</>
Copy
int_value = 254
str_value = "34.68"
complex_value = 3.14j

long_value_to_float = float(int_value)
str_value_to_float = float(str_value)
complex_value_to_float = float(abs(complex_value))

print(long_value_to_float)
print(str_value_to_float)
print(complex_value_to_float)

Output

254.0
34.68
3.14

As with int(), a complex number cannot be converted directly to float(). The example converts the magnitude returned by abs().

</>
Copy
print(float("10"))
print(float("10.75"))
print(float("-3.5"))
10.0
10.75
-3.5

Convert values to complex numbers in Python with complex()

complex(real) converts a real value to a complex number whose imaginary part is 0.

complex(real, imag) creates a complex number using the given real and imaginary parts.

example.py – Python Program

</>
Copy
real_value = 254
imaginary_value = 394

to_complex_only_real = complex(real_value)
to_complex = complex(real_value, imaginary_value)

print(to_complex_only_real)
print(to_complex)

Output

(254+0j)
(254+394j)

You can also convert a valid complex-number string. Do not include spaces around the + or - sign inside the string.

</>
Copy
z = complex("2+3j")
print(z)
print(type(z))
(2+3j)
<class 'complex'>

Convert Unicode code points to characters in Python with chr()

chr(x) converts an integer Unicode code point to the corresponding character.

example.py – Python Program

</>
Copy
int_value_1 = 69
int_value_2 = 81

int_to_character_1 = chr(int_value_1)
int_to_character_2 = chr(int_value_2)

print(int_to_character_1)
print(int_to_character_2)

Output

E
Q

The reverse operation is ord(), which converts a single character to its integer Unicode code point.

</>
Copy
print(ord("E"))
print(chr(9731))
69
☃

Convert values to string in Python with str()

str(x) converts x to a string. This is useful when you want to display a value, join it with other text, or write it as text output.

Following program demonstrates the conversion of float, int, complex number, tuple, list and dictionary to string.

example.py – Python Program

</>
Copy
float_value = 56.369
long_value = 6369742212323693323265
complex_value = (214 + 254j)
tuple_value = ("John","spy",42)
list_value = [1,'India',36.45,"New Delhi"]
dict_value = {'country':'India','capital':'New Delhi'}

float_value_to_string = str(float_value)
long_value_to_string = str(long_value)
complex_value_to_string = str(complex_value)
tuple_value_to_string = str(tuple_value)
list_value_to_string = str(list_value)
dict_value_to_string = str(dict_value)

print(float_value_to_string)
print(long_value_to_string)
print(complex_value_to_string)
print(tuple_value_to_string)
print(list_value_to_string)
print(dict_value_to_string)
print()
print(float_value_to_string + long_value_to_string + complex_value_to_string +
      tuple_value_to_string + list_value_to_string + dict_value_to_string)

Output

56.369
6369742212323693323265
(214+254j)
('spy', 42, 'John')
[1, 'India', 36.45, 'New Delhi']
{'country': 'India', 'capital': 'New Delhi'}

56.3696369742212323693323265(214+254j){'spy', 42, 'John'}[1, 'India', 36.45, 'New Delhi']{'country': 'India', 'capital': 'New Delhi'}

When converting a tuple to a string, Python keeps the tuple order. For a simple and predictable check, run this shorter example.

</>
Copy
tuple_value = ("John", "spy", 42)
text = str(tuple_value)

print(text)
print(type(text))
('John', 'spy', 42)
<class 'str'>

If you are building user-facing messages, f-strings are often clearer than converting each part manually.

</>
Copy
name = "Ravi"
score = 95

message = f"{name} scored {score} marks"
print(message)
Ravi scored 95 marks

Convert iterables to tuple in Python with tuple()

tuple(x) converts an iterable value x to a tuple. A tuple is ordered and immutable, so its elements cannot be changed after creation.

example.py – Python Program

</>
Copy
str_value = "hello"
str_to_tuple = tuple(str_value)

print(str_to_tuple)
print(str_to_tuple[0])
print(str_to_tuple[1])
print(str_to_tuple[2])
print(str_to_tuple[3])
print(str_to_tuple[4])

Output

('h', 'e', 'l', 'l', 'o')
h
e
l
l
o

The string is made up of characters and when the string is converted to tuple, the characters would become elements of the tuple.

You can also convert a list to a tuple when you want to prevent accidental item updates.

</>
Copy
items = ["pen", "book", "bag"]
items_tuple = tuple(items)

print(items_tuple)
('pen', 'book', 'bag')

Convert iterables to list in Python with list()

list(x) converts an iterable value to a list. If x is a string, Python iterates over its characters and places each character as a separate list element.

example.py – Python Program

</>
Copy
str_value = "hello"
str_to_list = list(str_value)
print(str_to_list)

Output :

['h', 'e', 'l', 'l', 'o']

Use split() instead of list() when you want words, not individual characters.

</>
Copy
sentence = "Python type conversion"
words = sentence.split()

print(words)
['Python', 'type', 'conversion']

Convert iterables to set in Python with set()

set(x) converts an iterable value to a set. A set stores unique elements and does not preserve a reliable display order.

If x is a string, Python iterates over its characters and keeps only unique characters in the newly formed set.

example.py – Python Program

</>
Copy
str_value = "hello Nemo!"
str_to_list = set(str_value)
print(str_to_set)

Output

{'h', 'o', 'l', ' ', '!', 'm', 'N', 'e'}

The set output order can vary between Python runs. Also, the variable name used in print() must match the variable that stores the set. A corrected version with deterministic output is shown below.

</>
Copy
str_value = "hello Nemo!"
str_to_set = set(str_value)

print(sorted(str_to_set))
[' ', '!', 'N', 'e', 'h', 'l', 'm', 'o']

Convert iterables to frozenset in Python with frozenset()

frozenset(x) converts an iterable value to an immutable set. It keeps unique elements like set(), but you cannot add or remove elements after creating it.

example.py – Python Program

</>
Copy
str_value = "hello Nemo!"
str_to_frozenset = frozenset(str_value)
print(str_to_frozenset)

Output

frozenset({' ', 'm', 'N', 'h', 'l', 'e', '!', 'o'})

Use frozenset() when you need a set-like collection that should not be changed, or when you need a hashable set-like value.

Convert pairs to dictionary in Python with dict()

dict(x) converts a sequence of key-value pairs into a dictionary. Each inner item must contain exactly two values: the key and the value.

Python Variable Data Type Conversion from list of tuples to dictionary

example.py – Python Program

</>
Copy
tupils_list = z = [('1','a'), ('2','b'), ('3','c')]
str_to_dict = dict(tupils_list)
print(str_to_dict)

Output

{'1': 'a', '2': 'b', '3': 'c'}

If the same key appears more than once, the later value replaces the earlier value.

</>
Copy
pairs = [("id", 101), ("name", "Asha"), ("id", 102)]
student = dict(pairs)

print(student)
{'id': 102, 'name': 'Asha'}

Convert values to Boolean in Python with bool()

bool(x) converts a value to either True or False. Empty values such as 0, "", [], (), {}, set(), and None convert to False. Most non-empty values convert to True.

</>
Copy
print(bool(0))
print(bool(""))
print(bool([]))
print(bool("False"))
print(bool(25))
False
False
False
True
True

Notice that bool("False") returns True because the string is not empty. If you need to interpret text such as "yes", "no", "true", or "false", compare the lowercase string yourself.

Python brackets and datatype conversion: (), [], and {}

Beginners often confuse brackets with conversion functions. Brackets create or access data structures, while functions such as tuple(), list(), and dict() perform conversion.

</>
Copy
# Parentheses: tuple, grouping, or function call
point = (10, 20)

# Square brackets: list or indexing
items = [10, 20, 30]
first_item = items[0]

# Curly braces: dictionary or set
student = {"name": "Meena", "age": 15}
unique_numbers = {1, 2, 3}

An empty pair of curly braces, {}, creates an empty dictionary, not an empty set. Use set() for an empty set.

Common Python datatype conversion mistakes

  • Using int("45.6") and expecting 45. Convert to float first only if that behaviour is intentional.
  • Expecting int(8.99) to round to 9. It returns 8.
  • Using list("hello world") when you need words. Use "hello world".split().
  • Expecting a set to preserve order. Sets are used for uniqueness, not ordered display.
  • Using bool("False") for text interpretation. Non-empty strings are truthy.
  • Passing a complex number directly to int() or float(). Convert its magnitude or real part explicitly if that is what you need.

Python datatype conversion practice examples

The following examples combine multiple conversions in the way they are usually used in programs.

</>
Copy
quantity_text = "3"
price_text = "19.50"

quantity = int(quantity_text)
price = float(price_text)
total = quantity * price

print(f"Total = {total}")
Total = 58.5
</>
Copy
csv_line = "red,green,blue"
colors = tuple(csv_line.split(","))

print(colors)
('red', 'green', 'blue')

Python datatype conversion FAQ

How do you convert the type of a value in Python?

Use a built-in conversion function for the target type. For example, use int("10") to convert a numeric string to an integer, float("10.5") to convert a decimal string to a float, and list("abc") to convert a string into a list of characters.

What is the difference between implicit and explicit type conversion in Python?

Implicit conversion is done automatically by Python, such as converting an integer to a float during arithmetic. Explicit conversion is done by the programmer using functions such as int(), str(), tuple(), or dict().

What is the difference between (), [], and {} in Python datatype examples?

() can create tuples, group expressions, or call functions depending on context. [] creates lists or accesses items by index. {} creates dictionaries when empty or when key-value pairs are used; it creates sets when comma-separated values are used without key-value pairs.

What are the main categories of Python data types used in conversion?

A practical beginner grouping includes numeric types, text type, sequence types, mapping type, set types, Boolean type, binary types, and None type. This tutorial focuses on common conversions among numbers, strings, tuples, lists, sets, frozen sets, dictionaries, characters, and booleans.

Does swapcase() perform Python datatype conversion?

No. swapcase() is a string method that returns a new string with uppercase letters changed to lowercase and lowercase letters changed to uppercase. It does not convert the value to another data type.

Editorial QA checklist for Python datatype conversion examples

  • Check that every conversion example uses the correct target type: int, float, complex, str, tuple, list, set, frozenset, dict, chr, or bool.
  • Confirm that output blocks match the code and use the output class.
  • Verify that examples involving sets do not depend on a fixed set display order unless sorted() is used.
  • Make sure Python 3 wording uses int instead of teaching long as a separate everyday type.
  • Check that examples explain likely errors such as ValueError from invalid numeric strings.

Python datatype conversion summary

In this Python Tutorial, we have learnt Python Variable Data Type Conversion. Use int(), float(), complex(), str(), tuple(), list(), set(), frozenset(), dict(), chr(), and bool() according to the target type you need. When converting input from users or files, always handle invalid values and check that the converted value means what your program expects.