Array in Python

Arrays are a fundamental part of all programming languages, it is a collection of elements of a single data type, for example, integer arrays, string arrays. Unlike arrays, each list can store elements with any data type and do everything the array can do. We can store integers, decimals, strings in the same list. Therefore, working with the list is quite flexible. However, in Python, there is no original array data structure. So we use Python lists instead of arrays.

An array of numeric values ​​is supported in Python by the array module.

Note: If you want to create an array really in Python, you need to use the array data structure of NumPy. To solve math problems, the NumPy array will be more efficient.

List and array modules in Python

You can manipulate the list as an array but cannot cast the element stored in the list. For example:

 a = [1, 3.5, "Hello"] 

If you create an array using an array module, all array elements must have the same number type.

 import array as arr 
a = arr.array ('d', [1, 3.5, "Hello"]) // Run this code to report an error

How to create array in Python?

From the above examples you can guess, we need to enter the array module to create arrays. For example:

 import array as arr 
a = arr.array ('d', [ 1.1 , 3.5 , 4.5 ]) print ( a )

The code on creating the array has type float. The word 'd' is type code, which determines the type of array in the creation process. Here are the common style codes:

TypeCython Type Type Minimum size in bytes 'b' signed char int 1 'B' unsigned char int 1 'u' Py_UNICODE 2 Unicode character 'h' signed short int 2 'H' unsigned short int 2 'i' signed int int 2 'I' unsigned int int 2 'l' signed long int 4 'L' unsigned long int 4 'f' float float 4 'd' double float 8

We will not discuss the different C data types in this article. We will use the code 'i' for integers and 'd' for decimals in the whole lesson.

Note: The code 'u' for Unicode characters is no longer accepted from Python version 3.3. Avoid using it when possible.

How to access array elements?

We use index to access array elements. Index also starts at 0, similar to the Python list.

 import array as arr a = arr . array ( 'i' , [ 2 , 4 , 6 , 8 ]) print ( "Phần tử đầu tiên:" , a [ 0 ]) print ( "Phần tử thứ 2:" , a [ 1 ]) print ( "Phần tử cuối cùng:" , a [- 1 ]) 

Run the program above:

 First element: 2 
Element 2: 4
Last element: 8

You can access a range of elements in the array, using the slice operator:.

 import array as arr numbers_list = [ 5 , 85 , 65 , 1 5 , 95 , 52 , 36 , 2 5 ] numbers_array = arr . array ( 'i' , numbers_list ) print ( numbers_array [ 2 : 5 ]) # Phần tử thứ 3 đến 5 print ( numbers_array [:- 5 ]) # Phần tử đầu tiên đến 4 print ( numbers_array [ 5 :]) # Phần tử thứ 6 đến hết print ( numbers_array [:]) # Phần tử đầu tiên đến cuối cùng 

When you run the above code, you will get the output:

 array ('i', [65, 15, 95]) 
array ('i', [5, 85, 65])
array ('i', [52, 36, 25])
array ('i', [5, 85, 65, 15, 95, 52, 36, 25])

Change, add element in Python array

Arrays can be changed, its elements can be changed in the same way as lists.

 import array as arr numbers = arr . array ( 'i' , [ 1 , 1, 2 , 5 , 7 , 9 ]) # thay đổi phần tử đầu tiên numbers [ 0 ] = 0 print ( numbers ) # Output: array('i', [0, 1, 2, 5, 7, 9]) # thay phần tử thứ 3 đến thứ 5 numbers [ 2 : 5 ] = arr . array ( 'i' , [ 4 , 6 , 8 ]) print ( numbers ) # Output: array('i', [0, 1, 4, 6, 8, 9]) 

Do you add an item to the list using append () or add some items using extend ():

 import array as arr numbers = arr . array ( 'i' , [3, 5, 7 ]) numbers . append ( 4 ) print ( numbers ) # Output: array('i', [3, 5, 7, 4]) # extend() nối vào cuối mảng numbers . extend ([ 5 , 6 , 7 ]) print ( numbers ) # Output: array('i', [3, 5, 7, 4, 5, 6, 7]) 

Two arrays can also be recombined into one by the + operator:

 import array as arr mang_le = arr . array ( 'i' , [ 3 , 5 , 7 ]) mang_chan = arr . array ( 'i' , [ 2 , 6 , 8 ]) numbers = arr . array ( 'i' ) # tạo mảng trống numbers = mang_le + mang_chan # Code by quantrimang.com print ( numbers ) # Output: array('i', [3, 5, 7, 2, 6, 8]) 

Delete element of array in Python

To delete one or more elements of the array we use the del command.

 import array as arr number = arr . array ( 'i' , [ 1 , 3 , 3 , 5 , 7 ]) del number [ 2 ] # xóa phần tử thứ 3 print ( number ) # Output: array('i', [1, 3, 5, 7]) del number # xóa toàn bộ mảng print ( number ) # Error: array 'number' is not defined 

You can use remove () to delete the given item or pop () to delete the item with the given index:

 import array as arr numbers = arr . array ( 'i' , [ 1 , 1 , 3 , 5 , 9 ]) numbers . remove ( 1 ) print ( numbers ) # Output: array('i', [1, 3, 5, 9]) print ( numbers . pop ( 2 )) # Output: 12 print ( numbers ) # Output: array('i', [1, 3, 9]) 

You can learn more about the Python array methods here.

When to use array?

List is more flexible than array, they can store elements with many different data types, including strings. List is also faster than array, so why use an array? If you have to perform array and matrix calculations, you should use the NumPy library. Unless you really need arrays (array modules may need to communicate with the C code), don't use them.

Previous post: Pakage in Python

3.5 ★ | 2 Vote

May be interested

  • 5 choose the best Python IDE for you5 choose the best Python IDE for you
    in order to learn well python, it is essential that you find yourself an appropriate ide to develop. quantrimang would like to introduce some of the best environments to help improve your productivity.
  • What is Python? Why choose Python?What is Python?  Why choose Python?
    python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages ​​for people who are first exposed to programming languages.
  • Module time in PythonModule time in Python
    python has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
  • Python data type: string, number, list, tuple, set and dictionaryPython data type: string, number, list, tuple, set and dictionary
    in this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
  • How to install Python on Windows, macOS, LinuxHow to install Python on Windows, macOS, Linux
    to get started with python, you first need to install python on the computer you are using, be it windows, macos or linux. below is a guide to installing python on your computer, specific to each operating system.
  • How to set up Python to program on WSLHow to set up Python to program on WSL
    get started with cross-platform python programming by setting up python on the windows subsystem for linux. here's how to set up python for wsl programming.
  • Multiple choice quiz about Python - Part 4Multiple choice quiz about Python - Part 4
    continue python's thematic quiz, part 4 goes back to the topic core data type - standard data types in python. let's try with quantrimang to try the 10 questions below.
  • How to use Closure in PythonHow to use Closure in Python
    in this article, tipsmake.com will work with you to learn about closure in python, how to define a closure and why you should use it. let's go find the answer!
  • Functions in PythonFunctions in Python
    what is python function? how is the syntax, components, and function types in python? how to create functions in python? these questions will be answered in the python lesson below.
  • How to use GPT-3 with PythonHow to use GPT-3 with Python
    feel free to use cool gpt-3 technology with your own python scripts using openai's handy api. here are details on how to use gpt-3 with python.