Thứ Năm, Tháng Hai 13, 2025
spot_img
HomeArrays in Python - QuanTriMang.com

Arrays in Python – QuanTriMang.com

What is an array in Python? How to use Python arrays? Let's find out with Quantrimang.com!

An array in Python is a collection of items stored at contiguous memory locations. The idea here is to store multiple items of the same type together. This action assists the user in calculating the position of each element more easily by adding an offset to the base value, i.e. the memory location of the first element in the array (usually expressed as name of the array).

To put it simply, you can imagine an array in Python as a series of stairs where each step has a value. Here, you can determine the position of any friend by counting the number of steps containing the value. Arrays can be handled by a module called array in Python. They can be useful when you only have to deal with one data type value. A user can view a list as an array. However, they cannot limit the type of elements saved in the list. If you create an array using the array module, all elements of the array must be of the same type.

Note: If you want to create real arrays in Python, you need to use NumPy's array data structure. To solve mathematical problems, NumPy arrays are more effective.

List and array modules in Python

You can manipulate lists like arrays, but you cannot cast elements stored in the list. For example:

a= [1, 3.5, "Hello"]

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

import array as arr
a = arr.array('d', [1, 3.5, "Hello"]) // Chạy code này sẽ báo lỗi

How to create arrays in Python?

As you can guess from the above examples, we need to import 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 above code creates an array of type float. The letter 'd' is the type code, which determines the type of the array during creation. Below are commonly used style codes:

Style code C Type Python Type Minimum size in bytes
'b' signed char int 1
'B' unsigned char int 1
'u' Py_UNICODE Unicode characters 2
'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 float. float 4
'd' double float. 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 decimal numbers throughout the lesson.

Note: Codename 'u' for Unicode characters is no longer accepted as of Python version 3.3. Avoid using it when possible.

How to access array elements?

We use index to access array elements. Index also starts from 0, similar to 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])

Running the above program we get:

Phần tử đầu tiên: 2
Phần tử thứ 2: 4
Phần tử cuối cùng: 8

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

import array as arr 

numbers_list = [5, 85, 65, 15, 95, 52, 36, 25] 
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 receive the following 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 elements in Python array

An array is mutable, its elements can change in the same way as a list.

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])

You can add an item to the list using append() or add several 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 joined into one using 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 array elements in Python

To delete one or more elements of an 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 remove a given item or pop() to remove an item with a 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])

Complexity of removing arrays in Python

In Python arrays, you have many ways to print the entire array with all the elements, but to print a specific range of elements from the array, you need to use the Slice operator. The slice operator is performed on the array along with a colon (:). To print the elements from the beginning to the array use [:Index]to print the elements at the end of the user [:-Index]to print elements from a specific index to the end user [Index:]to print elements within a range, use [Start Index:End Index] and to print the entire list using the slice operator, use [:]. Alternatively, to print the entire array in reverse order, use [::-1].

For example:

# Ví dụ chứng minh độ phức tạp khi xóa phần tử trong mảng 
# Chia tách phần tử trong mảng
 
# Nhập mô đun mảng
import array as arr
 
# Tạo danh sách
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
    print(i, end=" ")
 
# In các nhân tố của một mảng
# Dùng toán tử Slice 
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
 
# In các nhân tố từ điểm xác định trước tới cuối
Sliced_array = a[5:]
print("\nElements sliced from 5th "
      "element till the end: ")
print(Sliced_array)
 
# In các nhân tố từ điểm bắt đầu tới cuối
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)

Result:

Mảng ban đầu:
1 2 3 4 5 6 7 8 9 10
Tách các nhân tố trong mảng 3-8:
array('i', [4, 5, 6, 7, 8])

Tách nhân tố trong mảng từ thứ 5 tới cuối:
array('i', [6, 7, 8, 9, 10])

In tất cả các nhân tố bằng toán tử slice:
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Iterate over the elements in the array

You can use loop for in through all elements of an array. For example:
Print each item in the cars array:

for x in cars:
  print(x)

Array methods in Python

Python has a set of methods available for you to use on lists/arrays.

Method

Describe

append()

Adds an element to the end of the list

clear()

Remove all elements from the list

copy()

Returns a copy of the list

count()

Returns the number of elements with the specified value

extend()

Adds list (or any iterable) elements to the end of the current list

index()

Returns the index of the first element with the specified value

insert()

Adds an element to the specified position

pop()

Removes an element at a certain position

remove()

Removes the first item with a specific value

reverse()

Reverse the order of the list

sort()

Categorize list

Note: Python does not have built-in support for arrays; instead, you can use Python Lists.

Compare Lists and Arrays in Python

In Python, you can think of a list as an array. However, you cannot restrict the type of elements stored in a list. For example:

# phần tử của các kiểu khác nhau
a = [1, 3.5, "Hello"]

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

import array as arr
# Error
a = arr.array('d', [1, 3.5, "Hello"])

Result:

Traceback (most recent call last):
File "", line 3, in 
a = arr.array('d', [1, 3.5, "Hello"])
TypeError: must be real number, not str

When to use arrays?

Lists are more flexible than arrays, they can store elements with many different data types, including strings. Lists are also faster than arrays, so why use arrays? If you have to perform mathematical calculations on arrays and matrices, you should use the NumPy library.

So what are the use cases for arrays created from the Python array module?

Type array.array is just a small wrapper over C arrays that provides space-efficient storage of type C data types. If you need to allocate an array that you know will remain constant, arrays can run faster and be used. less memory than list.

Unless the array is not really needed (the array module may be needed to interfere with C code), using the array module here is not necessary.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments