Explain Codes LogoExplain Codes Logo

How do I declare an array in Python?

python
list-comprehensions
data-structures
performance-optimization
Alex KataevbyAlex Kataev·Nov 23, 2024
TLDR

In Python, you can use lists to create arrays:

# How many programmers does it take to change a light bulb? None, that's a hardware issue. my_list = [1, 2, 3]

For 2D arrays or matrices:

# I would tell you a joke about UDP...but you might not get it ;) my_matrix = [[1, 2], [3, 4]]

If performance and single-type data is a concern, consider array.array:

from array import array # Knock, knock. Who’s there? very long pause…. Java. my_array = array('i', [1, 2, 3])

Choose numpy for scientific computing or multidimensional arrays:

import numpy as np # If I had a cent for every time I forgot an item on my shopping list, I'd get a dollar by now! my_np_array = np.array([1, 2, 3])

Differences between arrays and lists

Though they appear similar, arrays and lists have distinct features:

  • Python lists: Dynamic in size, includes various types, and supports negative indexing
  • array.array: Requires homogeneous data for efficient storage and performance; consult the array module documentation

The right tool for the right job

Your choice depends upon the task:

  • Multi-purpose tasks or mixed types? - lists
  • Large data with type consistency? - array.array
  • Need super computational efficiency? - numpy

List and array: Tips and Tricks

Tips for seasoned Python users:

  • Initialize lists using list comprehensions:

    # Zero heroes zeroes = [0 for _ in range(10)]
  • Pre-allocate storage space for heavy data to increase efficiency.

  • Though Python is dynamically typed, enforce type discipline when needed every once in a while. Remember, consistency is a virtue!

Alternate data structures

Python offers several other handy structures:

  • deque from collections: For quick append and pop operations from both ends
  • heapq: For when you need to prioritize!
  • set: For when you absolutely abhor repetitions

Tailoring solutions

Consider the Python proficiency of the reader:

  • For beginners: Simple examples and explanations should suffice.
  • For the experienced ones: Time to dive deep into intricacies and performance-related aspects.