Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Python tutorial: Get started with Python arrays
Educative profile imageErin Schaffer
Erin Schaffer forEducative

Posted on • Originally published ateducative.io

     

Python tutorial: Get started with Python arrays

Python is one of the most popular programming languages. It’s used in many different fields like web development, data science, machine learning, and more. Arrays are an important data structure in Python. Arrays allow us to store multiple values at a time and perform actions on those values. In this Python tutorial, we’ll explore Python arrays, array operations, and more.

We’ll cover:

What are Python arrays?

A Python array is a container that can hold a number of elements of the same data type in one single variable. This allows us to store multiple elements of the same type together.

Arrays are very common. Most data structures use arrays to execute algorithms, and arrays are very commonly used in fields like data science and machine learning. We can use arrays when we want to manipulate data of a certain type. They’re very useful when working with large amounts of data because arrays can hold a large number of elements. An arrayelement is an item stored in an array. So the items “Spot”, “Max”, and “Sam” from ourdogs array are elements. Theindex refers to the numerical index location of each element. We can use the index to identify and access elements.

What are Python lists?

Although the two are sometimes confused, a Python list is different than a Python array. A list is a collection of items that contains data of different data types. This means that the first element of the list can be a string, the second element can be an integer, and the third can be a list of strings, etc. Lists are ordered, mutable, and their elements don’t need to be unique.

We can convert our Python lists to arrays using the NumPy Python library using one of the following NumPy array functions:

  • numpy.array()
  • numpy.asarray()

Create Python array

We can create a new array using the array module and theimport array command. Let’s take a look at an example Python program:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]print(dogs)=> ['Spot', 'Max', 'Sam', 'Charlie', 'Cooper', 'Duke', 'Bear', 'Buddy', 'Milo', 'Murphy']
Enter fullscreen modeExit fullscreen mode

Now, let’s take a look at the different operations we can perform on Python arrays.

Common array operations

Add elements

There are a couple of different ways to add elements to an array. We can append elements to the end of the array using theappend() method:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]dogs.append("Wrigley")print(dogs)=> ['Spot', 'Max', 'Sam', 'Charlie', 'Cooper', 'Duke', 'Bear', 'Buddy', 'Milo', 'Murphy', 'Wrigley']
Enter fullscreen modeExit fullscreen mode

We can use theinsert() method to add an element to a given index location within our array. Here’s an example:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]dogs.insert(1, "Wrigley")print(dogs)=> ['Spot', 'Wrigley', 'Max', 'Sam', 'Charlie', 'Cooper', 'Duke', 'Bear', 'Buddy', 'Milo', 'Murphy']
Enter fullscreen modeExit fullscreen mode

Access elements

We can access an array item by referring to its index number. For example, if we want to get the value of the first array item, we can use the following code:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]x = dogs[0]print(x)=> Spot
Enter fullscreen modeExit fullscreen mode

If we want to access a specific element and change that element, we access the index number and set it equal to the modified value. For example:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]dogs[0] = "Jack"print(dogs)=> ['Jack', 'Max', 'Sam', 'Charlie', 'Cooper', 'Duke', 'Bear', 'Buddy', 'Milo', 'Murphy']
Enter fullscreen modeExit fullscreen mode

Remove elements

There are a couple of different ways to remove elements of an array. We can use thepop() Python function to remove an element at a specified position. Let’s say we want to remove the last element of ourdogs array:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]dogs.pop(9)print(dogs)=> ['Spot', 'Max', 'Sam', 'Charlie', 'Cooper', 'Duke', 'Bear', 'Buddy', 'Milo']
Enter fullscreen modeExit fullscreen mode

We can use theremove() method to remove a specified element from an array. Here’s an example:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]dogs.remove("Duke")print(dogs)=> ['Spot', 'Max', 'Sam', 'Charlie', 'Cooper', 'Bear', 'Buddy', 'Milo', 'Murphy']
Enter fullscreen modeExit fullscreen mode

Find array length

We can use thelen() method to return the length of an array. If we want to return the number of elements in thedogs array, we can use the following code:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]x = len(dogs)print(x)=> 10
Enter fullscreen modeExit fullscreen mode

Sort Python array

We can use thesort() method to sort our array in ascending or descending order. If we want to sort our array in ascending order, we can use the following code:

numbers = [5, 13, 25, 2, 98, 56, 4, 8]numbers.sort()print(numbers)=> [2, 4, 5, 8, 13, 25, 56, 98]
Enter fullscreen modeExit fullscreen mode

To sort our array in descending order, we can use the following code:

numbers = [5, 13, 25, 2, 98, 56, 4, 8]numbers.sort(reverse=True)print(numbers)=> [98, 56, 25, 13, 8, 5, 4, 2]
Enter fullscreen modeExit fullscreen mode

Count elements

We can use thecount() method to return the number of elements with the specified value. For example, let’s say we want to return the number of times the value “Spot” appears in ourdogs array:

dogs = ["Spot", "Max", "Sam", "Charlie", "Cooper", "Duke", "Bear", "Buddy", "Milo", "Murphy"]x = dogs.count("Spot")print(x)=> 1
Enter fullscreen modeExit fullscreen mode

2D Python arrays

A 2D array, or a two-dimensional array, is when there’s an array within an array. In a standard array, each element has an index. In a 2D array, each element has two indices. Let’s move on to an example. Imagine we need to keep track of how the temperature changes throughout the day. We’ll take four temperatures: one in the early morning, one in the late morning, one in the afternoon, and one in the evening. We can store these temperatures in a 2D array.

  • Day one: 52, 60, 66, 63
  • Day two: 50, 58, 62, 60
  • Day three: 53, 61, 67, 64
  • Day four: 51, 59, 65, 62
temperatures = [[52, 60, 66, 63], [50, 58, 62, 60], [53, 61, 67,64], [51, 59, 65, 62]]
Enter fullscreen modeExit fullscreen mode

We can perform the same actions on 2D arrays as we can on standard arrays.

Wrapping up and next steps

Congrats on taking your first steps with Python arrays! Arrays are an important and common data structure. They have a wide range of uses and are commonly used to execute algorithms. There’s still a lot more to learn about the Python programming language. Some recommended concepts to cover next include:

  • Python dictionaries
  • Python tuples
  • Python strings
  • Python syntax

To get started learning these concepts and more, check out Educative’s learning pathPython for Programmers. In this path, you’ll start by learning the fundamentals of Python, and then move into more advanced concepts including modules and web-related tasks. By the end, you’ll have the advanced knowledge to confidently use Python in your next project.

Happy learning!

Continue learning about Python

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
bdcoder profile image
Bikash Jain
An Engineer Come Writer.
  • Location
    India
  • Joined

I have compared your Python Resources with GFG, Scaler Topics and with Programiz, I can say that out of these three Scaler Python Resources (scaler.com/topics/python/) and Yours content is well written.

I am happy that i found 2 gems.

Happy Learning!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Get hands-on with top tech skills. Level up your career.

Level up on in-demand tech skills - at your own speed.

Text-based courses with embedded coding environments help you learn without the fluff.

More fromEducative

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp