Mastering Python Data Types: A Practical Guide
Python Data Types
This guide walks you through the core data types in Python, illustrating how they work and how to convert between them.
Data Types in Python
Every value in Python is an object, and each object is an instance of a class that defines its type. Understanding these types is essential for writing clear, efficient, and reliable code.
Below we cover the most frequently used data types: numbers, lists, tuples, strings, sets, and dictionaries.
Python Numbers
Python’s numeric types include int, float, and complex. Use type() to inspect a value’s class and isinstance() to test membership in a class hierarchy.
a = 5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j, complex))
Output
5 is of type <class 'int'> 2.0 is of type <class 'float'> (1+2j) is complex number? True
Integers can be arbitrarily large, limited only by available memory. Floating‑point numbers are accurate to about 15 decimal places; for example, 1 is an integer while 1.0 is a float.
Complex numbers follow the form x + yj, where x is the real part and y the imaginary part. Sample values:
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
The float b was truncated to fit the precision limits.
Python List
Lists are ordered, mutable sequences that can contain elements of any type. Declared with square brackets, items are separated by commas:
a = [1, 2.2, 'python']
Use slicing to retrieve sub‑lists. Indices start at zero:
a = [5,10,15,20,25,30,35,40]
print("a[2] = ", a[2])
print("a[0:3] = ", a[0:3])
print("a[5:] = ", a[5:])
Output
a[2] = 15 a[0:3] = [5, 10, 15] a[5:] = [30, 35, 40]
Lists are mutable; elements can be reassigned:
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
Python Tuple
Tuples are ordered but immutable. They are often used to protect data and can offer slight performance advantages over lists because their size cannot change. Defined with parentheses:
t = (5,'program', 1+3j)
Slicing works, but reassignment raises an error:
t = (5,'program', 1+3j)
print("t[1] = ", t[1])
print("t[0:3] = ", t[0:3])
# t[0] = 10 # would raise TypeError
Output
t[1] = program t[0:3] = (5, 'program', (1+3j))
Python Strings
Strings are immutable sequences of Unicode characters. Use single or double quotes; triple quotes allow multiline literals.
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output
This is a string A multiline string
Slicing works, but attempting to modify a character triggers an error:
s = 'Hello world!'
print("s[4] = ", s[4])
print("s[6:11] = ", s[6:11])
# s[5] = 'd' # would raise TypeError
Output
s[4] = o s[6:11] = world
Python Set
A set is an unordered collection of unique items, defined with braces. Sets automatically eliminate duplicates and support set operations like union and intersection.
a = {5,2,3,1,4}
print("a = ", a)
print(type(a))
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
Duplicates are removed automatically:
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Because sets are unordered, indexing and slicing are not supported.
Python Dictionary
Dictionaries store key‑value pairs and are highly optimized for lookup by key. Keys and values can be of any hashable type.
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1])
print("d['key'] = ", d['key'])
# print("d[2] = ", d[2]) # would raise KeyError
Output
<class 'dict'> d[1] = value d['key'] = 2
Conversion Between Data Types
Python provides built‑in constructors for type conversion: int(), float(), str(), and more. Converting a float to an int truncates toward zero.
float(5) # 5.0
int(10.6) # 10
int(-10.6) # -10
String conversions require compatible representations:
float('2.5') # 2.5
str(25) # '25'
# int('1p') # ValueError
Sequences can be converted to one another:
set([1,2,3]) # {1, 2, 3}
tuple({5,6,7}) # (5, 6, 7)
list('hello') # ['h', 'e', 'l', 'l', 'o']
To create a dictionary from an iterable of pairs:
dict([[1,2],[3,4]]) # {1: 2, 3: 4}
dict([(3,26),(4,44)]) # {3: 26, 4: 44}
Python
- Understanding C++ Data Types: Fundamentals, Modifiers, and Best Practices
- C Data Types Explained: int, float, char, and More – A Complete Guide
- Mastering Python Type Conversion & Casting: A Comprehensive Guide
- Java Primitive Data Types: A Complete Guide with Examples
- Python Data Classes: Streamline Data Management with Modern Syntax
- Verilog Data Types: Bits, Wires, and Logic Values Explained
- Understanding C Data Types: A Comprehensive Guide
- Understanding MATLAB Data Types: A Comprehensive Guide
- Comprehensive Guide to C# Data Types: Value, Reference, and Pointer
- Python Variable Types: Understanding and Using Data Types