# Arrays in Python

[Python](https://blog.bytescrum.com/exploring-pythons-core-from-basics-to-behind-the-scenes)'s [`array`](https://docs.python.org/3/library/array.html) module, a dedicated tool, enables efficient creation and manipulation of [arrays](https://techvidvan.com/tutorials/python-array-module/). Unlike lists, [arrays](https://www.linode.com/docs/guides/python-arrays/) store elements of a uniform data type like integers, floats, or characters, offering better [memory](https://help.ivanti.com/res/help/en_US/IWC/2022/Help/Content/44564.htm) efficiency and performance. This guide will cover how to use the [`array`](https://www.codingninjas.com/studio/library/what-are-arrays-in-python) module in [Python](https://blog.bytescrum.com/python-data-types-categorization-and-exploration), from creation to manipulation, to harness their power in programming.

## What is an Array?

"*An* [*array*](https://physics.nyu.edu/pine/pymanual/html/chap3/chap3_arrays.html) *is a container that holds a fixed number of items of the same type, used in most data structures for algorithm implementation. Each element in an* [*array*](https://www.edureka.co/blog/arrays-in-python/) *has a numerical index, which is used to identify its location within the* [*array*](https://trainings.internshala.com/blog/what-is-python-array/)."

### [**Array**](https://www.reddit.com/r/bigdata/comments/xud21w/can_you_have_multiple_data_types_in_one_array_in/?onetap_auto=true) **Representation**

[![Array Representation](https://cdn.hashnode.com/res/hashnode/image/upload/v1693980544989/689e0c3f-8033-4ab1-831a-13c93ebf043c.png align="center")](https://www.bytescrum.com/)

* The index begins at **0**.
    
* With an [array](https://jakevdp.github.io/PythonDataScienceHandbook/02.01-understanding-data-types.html) length of **10**, it can hold **10** items.
    
* The index of each element can be used to retrieve it. We can, for instance, get an element at index **6** as **92**.
    

## **How do you create an** [**array**](https://www.toppr.com/guides/python-guide/references/methods-and-functions/array/python-array-of-numeric-values/)**?**

To create an [array](https://www.tutorialspoint.com/python/python_arrays.htm) in [Python](https://blog.bytescrum.com/mastering-python-operators-part-1), specify the type code and pass the elements as a list or iterable. Common type codes include

* **'i' for signed integer**
    
* **'f' for floating-point**
    
* **'d' for double-precision floating-point**
    
* **'c' for character.**
    

### `'i'`: Signed integer

```python
import array
int_array = array.array('i', [1, 2, 3, 4, 5])
```

### `'f'`: Floating-point

```python
  import array
  float_array = array.array('f', [1.0, 2.5, 3.7, 4.2, 5.8])
```

### `'d'`: Double-precision floating-point

```python
  import array
  double_array = array.array('d', [1.0, 2.5, 3.7, 4.2, 5.8])
```

### `'c'`: Character

```python
import array
char_array = array.array('c', b'Hello')
```

## **How to access an** [**array**](https://www.scaler.com/topics/array-in-python/) **of elements?**

[Arrays](https://www.guru99.com/python-arrays.html) are zero-indexed, which means that the first element has an index of **0**, the second element has an index of **1**, and so on.

```python
my_array = [10, 20, 30, 40, 50]
element = my_array[2]  # Accessing the third element (30)
```

## What are the two main types of "[arrays](https://numpy.org/doc/stable/user/basics.types.html)" in [Python](https://www.geeksforgeeks.org/python-arrays/), and how do they differ?

In [Python](https://www.w3schools.com/python/python_arrays.asp), there are two main types of "[**arrays**](https://stackoverflow.com/questions/4855774/how-to-create-array-of-the-certain-type-in-python)":

* **Lists**
    
* [`array`](http://www.learningaboutelectronics.com/Articles/How-to-find-the-data-type-of-an-array-in-Python.php) Module [Arrays](https://datatrained.com/post/python-array-easy-guide/)
    

### **Lists**

*"Lists are one of the most fundamental data structures in* [*Python*](https://docs.python.org/3/library/array.html)*. They are ordered collections of items, which can be of different* [*data types*](https://germanna.edu/sites/default/files/2022-03/Python%20-%20Variables%20and%20Data%20Types.pdf)*, and they are mutable, meaning you can change their contents."*

* The most popular and flexible collection data type in [Python](https://www.tutorialspoint.com/python_data_structure/python_arrays.htm) is a list.
    
* They can include members of many [data types](https://pythonclassroomdiary.files.wordpress.com/2019/06/datatype.pdf), such as integers, floats, texts, and even other lists. They are ordered and changeable (can be altered).
    
* Square brackets **\[\]** are used to build lists, which may then be readily updated using several techniques.
    

```python
    my_list = [1, 2, 3, 4, 5]
      #Accessing Elements: 
      # Elements in a list are accessed by their index, starting from 0 for the first element.
    first_element = my_list[0]  # Access the first element
```

**Advantages**: Lists are versatile data storage and manipulation tools that can accommodate mixed [data types](https://www.purdue.edu/hla/sites/varalalab/wp-content/uploads/sites/20/2018/03/Lecture_8.pdf) and are suitable for most general-purpose tasks.

### [`array`](https://blog.hubspot.com/website/python-array) Module [Arrays](https://www.educative.io/answers/how-to-create-an-array-with-a-defined-data-type-in-python)

[Python](https://www.javatpoint.com/python-arrays) has a unique form of [array](https://www.studytonight.com/python-howtos/how-to-declare-an-array-in-python) that is provided via the [array](https://pimylifeup.com/python-arrays/) module.

* When dealing with items of the same data type, [arrays](https://favtutor.com/blogs/python-array-vs-list) formed with the [array](https://www.mygreatlearning.com/blog/python-array/) module are more [memory](https://saturncloud.io/blog/how-to-optimize-memory-and-time-usage-of-an-algorithm-in-python/)\-efficient and performant than lists.
    
* They are frequently employed in situations involving numerical data and other circumstances in which [memory optimization](https://datagy.io/python-array-vs-list/) and efficiency are crucial.
    

```python
from array import array
int_array = array('i', [1, 2, 3, 4, 5])
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">When creating an <a target="_blank" rel="noopener noreferrer nofollow" href="https://learnpython.com/blog/python-array-vs-list/" style="pointer-events: none">array</a> using the <a target="_blank" rel="noopener noreferrer nofollow" href="https://hackr.io/blog/python-arrays" style="pointer-events: none">array</a> module, you must choose a data type for each element and ensure that every element in the <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.atatus.com/blog/python-arrays/" style="pointer-events: none">array</a> belongs to that type.</div>
</div>

**Advantages**: [Arrays](https://introcs.cs.princeton.edu/python/14array/) are useful when you need to work with large datasets of a single data type, such as numerical data, and you want to optimize [memory](https://www.herevego.com/data-structures-1/) usage.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Lists and <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.pluralsight.com/guides/different-ways-create-numpy-arrays" style="pointer-events: none"><code>array</code></a> module <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.codementor.io/blog/python-array-cavmg6yr36" style="pointer-events: none">arrays</a>. Lists are versatile, can accommodate mixed <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.aees.gov.in/htmldocs/downloads/XI_Class_Content_Computer_Science/4-Ppt.pdf" style="pointer-events: none">data types</a>, and are suitable for most general-purpose tasks. <a target="_blank" rel="noopener noreferrer nofollow" href="https://stackoverflow.com/questions/10558670/how-does-python-have-different-data-types-in-an-array" style="pointer-events: none">Arrays</a> are useful for large datasets of a single data type and for optimizing <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.pythoninformer.com/python-language/data-structures/arrays/" style="pointer-events: none">memory</a> usage.</div>
</div>

## What are the different categories or types of [array](https://intellipaat.com/blog/tutorial/python-tutorial/python-arrays/) methods?

There are several ways to work with [arrays](https://builtin.com/data-science/how-to-create-list-array-python). Typical approaches include

* **Append(x)**: Add an item to the end of the [array](https://www.educative.io/answers/array-operations-in-python).
    
* **Extend (iterable**): Extend the [array](https://dbader.org/blog/python-arrays) with elements from an iterable.
    
* **Insert(i, x)**: Insert an item at a specific position.
    
* **Remove (x)**: Remove the first occurrence of a value.
    
* **Pop(\[i\])**: Remove and return an item at a specific position.
    
* **Index(x)**: Return the first index of the specified value.
    
* **Count(x)**: Return the number of occurrences of a value.
    
* **Reverse()**: Reverse the order of elements in the [array](https://realpython.com/python-data-structures/).
    
* **Sort ()**: Sort the elements in the [array](https://www.askpython.com/python/array/python-array-examples) (only for numeric types).
    

### **Append(x)**: Add an item to the end of the array.

The `append()` method adds a single element to the end of an existing [array](https://www.askpython.com/python/array/python-array-examples) or list, modifying the original without creating a new one.

* It's efficient, doesn't return a new list, and can be used for dynamic data manipulation and collection building.
    

```python
my_list = [1, 2, 3]
my_list.append(4)  # Adding the item 4 to the end of the list
print(my_list)     # Output: [1, 2, 3, 4]
```

### **Extend (iterable**): Extend the [array](https://www.quora.com/What-is-an-array-and-list-in-Python) with elements from an iterable.

The `extend(iterable)` method is a versatile tool for extending an [array](https://iq.opengenus.org/array-in-python/) with elements from another iterable.

* It is used to merge two [arrays](https://www.linode.com/docs/guides/python-arrays/), concatenate lists, or merge data from different sources, preserving their order and ensuring efficient and unique content.
    

```python
original_list = [1, 2, 3]
new_elements = [4, 5, 6]
original_list.extend(new_elements)  # Extending the original list
print(original_list)  # Output: [1, 2, 3, 4, 5, 6]
```

### **Insert(i, x)**: Insert an item at a specific position.

The `insert(i, x)` method in [Python](https://www.programiz.com/python-programming/array) inserts a new item at a specified position within an existing [array](https://www.educba.com/python-array-functions/) or list.

* It modifies the original [array](https://hackr.io/blog/python-arrays) and requires both the index and item.
    
* This method is useful for sorted lists or collections but may be less efficient for longer lists.
    

```python
my_list = [1, 2, 3, 5]
my_list.insert(3, 4)  # Inserting the number 4 at index 3
print(my_list)  # Output: [1, 2, 3, 4, 5]
```

### Pop(\[i\]): Remove and return an item at a specific position

The `pop([i])` method in [Python](https://www.freecodecamp.org/news/python-array-tutorial-define-index-methods/) is used to remove and return an item at a specific position within an [array](http://www.learningaboutelectronics.com/Articles/How-to-find-the-data-type-of-an-array-in-Python.php) or list.

* It modifies the original [array](https://careerkarma.com/blog/python-array/) by removing the specified element and returning it.
    
* The time complexity is **<mark>O(n)</mark>**, and it is commonly used for stack or queue data structures.
    

```python
my_list = [1, 2, 3, 4, 5]
popped_item = my_list.pop(2)  # Removing and returning the item at index 2 (value 3)
print(my_list)               # Output: [1, 2, 4, 5]
print(popped_item)           # Output: 3
```

### **Index(x)**: Return the first index of the specified value.

The `index(x)` method is a [Python](https://www.simplilearn.com/tutorials/python-tutorial/python-arrays) function that finds the first occurrence of a specific value within an [array](https://www.faceprep.in/python/arrays-in-python/) or list.

* It searches through the [array](https://www.youtube.com/watch?v=tHUNg8GdRQs&ab_channel=Intellipaat) from the beginning and returns the first element matching the value.
    
* The time complexity is **<mark>O(n)</mark>**, and it can be used for exact matches or complex criteria.
    

```python
my_list = [1, 2, 3, 2, 4]
index = my_list.index(2)  # Finding the index of the first occurrence of 2
print(index)             # Output: 1 (Index of the first '2' in the list)
```

### count(x): Return the number of occurrences of a value.

The `count(x)` method is a useful method for counting occurrences of a specific value within an [array](https://www.biganalytics.me/2023/01/Array-Types-Python.html) or list.

* It iterates through the [array](https://www.w3resource.com/python/library/python_array_module.php), returns an integer, and has a time complexity of **<mark>O(n)</mark>** in the worst case.
    
* Negative indices can be used for counting unique values.
    

```python
my_list = [1, 2, 3, 2, 4, 2]
count = my_list.count(2)  # Counting the number of occurrences of '2'
print(count)             # Output: 3 (There are 3 occurrences of '2' in the list)
```

### **Reverse()**: Reverse the order of elements in the [array](https://code-knowledge.com/python-introduction-array/).

The `reverse()` method is an efficient and **<mark>O(n)</mark>** time-efficient way to reverse the order of elements in an [array](https://www.digitalocean.com/community/tutorials/python-add-to-array) or list.

* It works with [arrays](https://www.techbeamers.com/python-arrays/) of different [data types](https://www.tutorialspoint.com/python/pdf/python_variable_types.pdf) and does not create a new reversed copy.
    
* It is useful for displaying data in reverse chronological order or sorting data.
    

```python
my_list = [1, 2, 3, 4, 5]
my_list.reverse()  # Reversing the order of elements
print(my_list)    # Output: [5, 4, 3, 2, 1]
```

### **Sort ()**: Sort the elements in the [array](https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/BasicArrayAttributes.html) (only for numeric types).

The `sort()` method is a powerful tool for sorting elements in an [array](https://codeinstitute.net/global/blog/python-arrays/) or list, typically for numeric types.

* It modifies the original [array](https://techaffinity.com/blog/python-arrays-array-methods/), rearranging its elements, and is generally efficient with a time complexity of **<mark>O(n log n).</mark>**
    
* It can be used for other [data types](https://web.engr.oregonstate.edu/~webbky/ENGR102_files/Class_11_PythonDataTypes.pdf) with defined comparison operations.
    

```python
num_list = [4, 1, 3, 2, 5]
num_list.sort()  # Sorting the list in ascending order
print(num_list)  # Output: [1, 2, 3, 4, 5]
```

## Examples of [Python](https://www.edureka.co/blog/arrays-in-python/) [Arrays](https://en.wikipedia.org/wiki/Array_(data_type))

### Example 1: Create a To-Do List for a [Python](https://www.datacamp.com/tutorial/python-arrays) list

```python
# Create an empty to-do list as a Python list
to_do_list = []

# Add tasks to the list
task1 = {
    "name": "Buy groceries",
    "due_date": "2023-09-10",
    "priority": "High"
}

task2 = {
    "name": "Prepare presentation",
    "due_date": "2023-09-15",
    "priority": "Medium"
}

task3 = {
    "name": "Exercise",
    "due_date": "2023-09-07",
    "priority": "Low"
}

to_do_list.append(task1)
to_do_list.append(task2)
to_do_list.append(task3)

# Print the to-do list
print("Today's To-Do List:")
for task in to_do_list:
    print(f"Task: {task['name']}")
    print(f"Due Date: {task['due_date']}")
    print(f"Priority: {task['priority']}")
    print("-" * 30)

# Modify a task
to_do_list[0]["priority"] = "Medium"

# Remove a task
to_do_list.pop(2)

# Updated To-Do List
print("\nUpdated To-Do List:")
for task in to_do_list:
    print(f"Task: {task['name']}")
    print(f"Due Date: {task['due_date']}")
    print(f"Priority: {task['priority']}")
    print("-" * 30)
```

### Example 2: Create a `float` [array](https://press.rebus.community/programmingfundamentals/chapter/arrays-and-lists/) for temperature measurements using the [`array`](https://www.upgrad.com/blog/python-array-vs-list-differences-use-cases/) module.

```python
from array import array

# Create an array of temperature measurements (floats)
temperature_data = array('f', [23.5, 24.0, 22.8, 25.2, 23.7])

# Calculate the average temperature
average_temperature = sum(temperature_data) / len(temperature_data)

# Find the maximum temperature
max_temperature = max(temperature_data)

# Print the results
print("Temperature Data:")
print(temperature_data)
print(f"Average Temperature: {average_temperature}°C")
print(f"Maximum Temperature: {max_temperature}°C")
```

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent"><a target="_blank" rel="noopener noreferrer nofollow" href="https://www.programiz.com/python-programming/array" style="pointer-events: none">Python</a> offers two main approaches to working with arrays: lists and array modules. Lists are dynamic <a target="_blank" rel="noopener noreferrer nofollow" href="https://datagy.io/python-array-vs-list/" style="pointer-events: none">arrays</a> that accommodate various <a target="_blank" rel="noopener noreferrer nofollow" href="https://mrcet.com/downloads/digital_notes/ECE/II%20Year/DATA%20STRUCTURES%20USING%20PYTHON.pdf" style="pointer-events: none">data types</a> and offer manipulation methods like append(), extend(), insert(), and remove(). They are versatile and widely used for general-purpose data storage and manipulation tasks. The <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.gkindex.com/python-tutorial/python-array-types.jsp" style="pointer-events: none">array</a> module, part of the standard library, facilitates the creation of homogeneous <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.w3schools.com/python/python_arrays.asp" style="pointer-events: none">array</a>s, which are <a target="_blank" rel="noopener noreferrer nofollow" href="https://totalview.io/blog/what-is-memory-optimization" style="pointer-events: none">memory</a>-efficient and suitable for handling extensive datasets of uniform <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.slideshare.net/NehaSpillai1/python-data-typespdf" style="pointer-events: none">data types</a>.</div></details>
