In Python, the terms “array,” “list,” and “tuple” refer to different types of data structures, each with its own characteristics and use cases. Let’s Understand the differences between these data structures in Python.
Here’s the syntax for creating arrays, lists, and tuples in Python:
Array (using NumPy):
import numpy as np
# Creating an array from a list
my_array = np.array([1, 2, 3, 4, 5])
List
# Creating an empty list
my_list = []
# Creating a list with values
my_list = [1, 2, 3, 4, 5]
Tuple
# Creating an empty tuple
my_tuple = ()
# Creating a tuple with values
my_tuple = (1, 2, 3, 4, 5)
Note: arrays require the NumPy library, so you need to import it before creating an array. Lists and tuples are built-in to Python and don’t require any additional imports.
Here’s a tabular comparison of Python arrays, lists, and tuples:
Array | List | Tuple | |
---|---|---|---|
Mutability | Mutable | Mutable | Immutable |
Homogeneity | Homogeneous | Heterogeneous | Heterogeneous |
Size | Fixed | Dynamic | Fixed |
Indexing | Zero-based | Zero-based | Zero-based |
Slicing | Supported | Supported | Supported |
Denoted by | NumPy library | Square brackets | Parentheses |
Use cases | Numerical computations, homogeneous data | Storing ordered collections, modifying elements | Storing fixed collections, immutability, dictionary keys |
Python array vs list vs tuple example
Here are some examples that demonstrate the usage of arrays, lists, and tuples in Python:
Array (using NumPy):
import numpy as np
# Creating an array from a list
my_array = np.array([1, 2, 3, 4, 5])
# Accessing elements
print(my_array[0]) # Output: 1
# Modifying an element
my_array[1] = 10
print(my_array) # Output: [1, 10, 3, 4, 5]
List:
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Accessing elements
print(my_list[0]) # Output: 1
# Modifying an element
my_list[1] = 10
print(my_list) # Output: [1, 10, 3, 4, 5]
# Appending elements
my_list.append(6)
print(my_list) # Output: [1, 10, 3, 4, 5, 6]
Tuple:
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
# Accessing elements
print(my_tuple[0]) # Output: 1
# Tuples are immutable, so modifying an element throws an error
# my_tuple[1] = 10 # Raises a TypeError
# Tuple unpacking
a, b, c = my_tuple[:3]
print(a, b, c)
Output:
In these examples, you can observe how to create arrays, lists, and tuples, access their elements using indexing, and modify elements (for mutable structures like arrays and lists). Tuples, being immutable, cannot have their elements modified once created.
Do comment if you have any doubts or suggestions on this Python comparison topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.