View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Arrays in Python: What are Arrays in Python & How to Use Them?

By Rohit Sharma

Updated on Jan 08, 2024 | 9 min read | 6.3k views

Share:

Python has emerged as a top programming language in terms of capabilities and usage around the world. Today, we are here to make you familiar with one of the simplest data structures for coding, i.e. arrays. 

So if you wish to learn about array in Python, keep reading this tutorial till the end to understand how to find the length of an array in Python. 

Explaining Python array

An array in Python refers to a collection that has multiple items saved together in contiguous memory chunks. Simply put, these locations hold many items of identical data type in a sequential arrangement. Let us understand this with an example: Imagine a fleet of stairs where each step denotes a value. And suppose that your friends are standing on different steps of this stairway. You can find the location of any one of your friends by simply knowing the count of the stair they are standing on. 

Python has a specific module called “array,” which you can use to manipulate specific values. You can create lists where all elements must have the same data type. With a data structure like an array, you are able to access numerical data from a defined series, fetching the required values by specifying an index number. (Note: The index begins from 0, and the stored items are called elements).  

Furthermore, you can change the array and perform several data manipulations, depending on your needs. But before we explore that in detail, we should address a common point of consumption.

Learn Data Science Courses online at upGrad

Although both Python arrays and lists store values in a similar manner, there exists a fundamental distinction between the two. While a list stores anything from integers to strings, an array can only have single value types. Therefore, you come across an array of strings, an array of integers, and so on. 

Arrays in Python

Arrays are fundamental data structures in computer programming that allow us to store and manipulate a collection of elements. In Python, arrays are versatile and powerful tools that enable us to handle large datasets efficiently. In this thorough guide, we will explore the concepts of arrays in Python, including sorted arrays and NumPy arrays.

Moreover, in Python, an array is a assemblage of elements of the type of data that is similar. Unlike lists, arrays are fixed in size and provide efficient memory allocation. We can even access individual elements of an array using their indices.

Creating Arrays

Python provides various ways to create arrays. One common method is to use the built-in array module, which requires importing the module and specifying the array’s data type. Another popular approach is to utilize the NumPy library, which offers a powerful array object called ndarray.

Checkout: Python Open Source Project & Topics

When and Why do We use Arrays?

We typically utilize the Python array module for purposes like interfacing with code written C. Arrays offer an easier way of storing C-style data types faster and with less memory space. 

Moreover, a combination of arrays with Python is also time-efficient. It reduces the overall size of your code and enables you to avoid problematic syntax, a major concern with other languages. 

For instance, if you had to store 100 variables with different names, it makes sense to store them as integers (1-100). It is a far better option to save them using an array instead of spending time remembering their names. 

Sorted Array Python

Sorting Arrays:

Sorting an array is a common operation in many programming tasks including sorted array Python. Python provides several methods for sorting arrays efficiently. One approach is to use the sorted() function, which returns a new sorted list without modifying the original array.

Example:

my_array = [5, 2, 8, 1, 9]

sorted_array = sorted(my_array)

print(sorted_array) # Output: [1, 2, 5, 8, 9]

Sorting NumPy Array in Python:

If you are working with NumPy array in Python, you can use the np. sort() function to sort the elements in arising/ascending order. Additionally, you can specify the axis parameter to sort the elements along a specific axis of a multi-dimensional array.

Example:

import numpy as np
my_array = np.array([5, 2, 8, 1, 9])
sorted_array = np.sort(my_array)
print(sorted_array) # Output: [1 2 5 8 9]

NumPy Arrays in Python:

NumPy is a powerful Python library that supports large, multi-dimensional arrays and matrices. NumPy arrays, also known as ndarrays, are highly efficient and allow for fast mathematical operations on the data.

Creating NumPy Arrays:

NumPy arrays can be created using various methods, such as converting lists or tuples to arrays, using built-in functions like zeros() and ones(), or reading data from external files.

Example:

import numpy as np
my_list = [1, 2, 3, 4, 5]
numpy_array = np.array(my_list)
print(numpy_array) # Output: [1 2 3 4 5]

Manipulating NumPy Arrays:

NumPy provides a wide range of functions for manipulating arrays. You can reshape, transpose, concatenate, and perform various mathematical operations on NumPy arrays.

Example:

import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
concatenated_array = np.concatenate((array1, array2))
print(concatenated_array) # Output: [1 2 3 4 5 6]

Arrays play a crucial role in Python programming, providing efficient ways to handle and manipulate data collections. Whether sorting arrays using the built-in sorted() function or utilizing the power of NumPy arrays, understanding the concepts of arrays in Python is essential for tackling complex programming tasks. By mastering arrays, you can unlock the full potential of Python and unleash your creativity in solving real-world problems. So, explore the world of arrays in Python to elevate your programming skills.

Our learners also read: Learn Python Online Course Free

Using array in Python

Let us take it one step at a time:

  1. Import the array module
  2. Create an array list (Specify the data type and value list as arguments)
  3. Add elements to the array using insert() and append()
  4. Start accessing elements 
  5. Update elements, as desired (Slice, change, remove)
  6. Search elements
  7. Find the array’s length

Now that you are aware of the different operations of using an array in Python, let us look at the sample code. 

  • To import the module, you simply use the ‘import’ command followed by the qualifier — let this be ‘jam’. 

import array as jam 

a = jam.array(‘o’,[1.2,3.6,4.7])
print (a)
This would display the following output:
array(‘o’,[1.2,3.6,4.7])
  • If you want to access a specific element of an array, you can use a code like this:

    import array as cam
    
    b = cam.array(‘i’,[1,3,5,7])
    
    print(“1st element:”,b[0])
    
    print(“2nd element:”, b[1])
    
    print(“Last element:”, b[-1])

The output would be shown as follows:

First element: 1

Second element: 3

Last element: 7

The following sample code will help you understand how to slice a part of the Python array

import array as mac

  • numbers_list = [22, 5, 42, 5, 52, 48, 62, 5]
    
    numbers_array = mac.array(‘j’,numbers_list)
    
    print(numbers_array[3:6]) # 4th to 6th
    
    print (numbers_array[:-5]) # beginning to 4th
    
    print (numbers_array[4:]) #5th to end
    
    print (numbers_array[:]) #beginning to end 
    
    This code will give you an output with specific integer values that you mentioned; see below:
    
    array(‘j’,[5, 52, 48])
    
    array(‘j’,[22, 5, 42])
    
    array(‘j’,[52, 48, 62, 5])
    
    array(‘j’,[22, 5, 42, 5, 52, 48, 62, 5)
  • Since a Python array is mutable, you can alter the items, add more elements, and remove others. Check out these examples: 

    import array as pac
    
    numbers = pac.array( ‘m’, [5, 10, 7, 1, 2, 3])                           
    
    #to change the first element 
    
    numbers[0] = 6
    
    print(numbers) 
    
    # Output: 
    
    array(‘m’ , [6, 10, 7, 1, 2, 3])
    
    #to change the fourth element to fifth element
    
    numbers[3:4] = pac.array( ‘m’, [8, 9, 4])
    
    Then, write the command to print the output array.
    
    # Output: 
    
    array(‘m’, [6, 10, 7, 8, 9, 4]) 

If you want to add a new item to the array, you can use the append() method. Alternatively, you can add many new items using the extend() method. We have demonstrated this for more clarity:

import array as dac

numbers = dac.array(‘i’, [3, 4, 5])

numbers.append(6)

Upon printing the output, you will get: 

#Output: array(‘i’, [3, 4, 5, 6])

# extend() to append iterable items to the end

numbers.extend[7,8,9])

Again, print the output to get the array:

array(‘i’, [3, 4, 5, 6, 7, 8, 9])

Similarly, you can remove one or more items using the del statement in Python. Let’s use the same array for this demonstration. 

del number[1] # to remove second element

print number() 

#Output:

array ( ‘i’, [3, 5, 6, 7, 8, 9])

You can also use the remove() function to delete a specific item and implement pop() to remove any given index. 

numbers.remove(8)

print(numbers.pop(4))number

array ( ‘i’, [3, 5, 6, 7, 9])

  • If you intend to search for a particular element, you can use index(), an in-built method in Python that returns the index of the first occurrence of the argument value.

With this, we have given you a refresher on what are arrays in Python and their usage. You may also be interested in finding the array length. Here, length refers to how many elements are present in the Python array. You can use the len() function to determine the length. It is as simple as inputting the len(array_name) statement, and a value (integer) will be returned. 

Take, for example, this array:

a=arr.array(‘f’, [2.1, 4.1, 6.1, 8.1])

len(a)

#Output: 4

As you can see, the value returned is equal to the number of elements in the Python array.

Check out all trending Python tutorial concepts in 2024.

Conclusion 

Now you know what are arrays in Python, their usage, along with how to find the length of the array in Python. This information will help you strengthen your Python programming skills. So, keep practising!

If you are curious to learn more about data science, check out IIIT-B & upGrad’s Executive PG Program in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree18 Months
View Program

Placement Assistance

Certification8-8.5 Months
View Program

Frequently Asked Questions (FAQs)

1. Explain the addition and deletion operation in Python arrays?

2. What are the advantages of arrays?

3. When is an array preferred over other data structures?

Rohit Sharma

690 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

View Program
Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

18 Months

View Program
upGrad Logo

Certification

3 Months

View Program