Python Arrays Explained
Python Arrays Explained
In Python, an array is an ordered collection, represented by the built-in list
. Array elements can be of any data type, including numbers, strings, and Boolean values. This article provides a detailed introduction to Python arrays, including operations such as creating, accessing, modifying, and deleting arrays.
Creating Arrays
In Python, you can create arrays in the following ways:
1. Using []
to create an empty array
arr = []
print(arr) # Output: []
2. Using the list()
function to create an array
arr = list()
print(arr) # Output: []
3. Using []
to create an array
arr = [1, 2, 3, 4, 5]
print(arr) # Output: [1, 2, 3, 4, 5]
4. Use the range()
function to create an array
arr = list(range(1, 6))
print(arr) # Output: [1, 2, 3, 4, 5]
Accessing Array Elements
You can use indices to access elements in an array, starting at 0. For example:
arr = [1, 2, 3, 4, 5]
print(arr[0]) # Output: 1
print(arr[2]) # Output: 3
Modifying Array Elements
You can modify elements in an array by indexing. For example:
arr = [1, 2, 3, 4, 5]
arr[1] = 10
print(arr) # Output: [1, 10, 3, 4, 5]
Adding Elements to an Array
You can use the append()
method to add new elements to an array. For example:
arr = [1, 2, 3]
arr.append(4)
print(arr) # Output: [1, 2, 3, 4]
Deleting array elements
You can use the del
keyword or the remove()
method to delete elements from an array, for example:
arr = [1, 2, 3, 4, 5]
del arr[1]
print(arr) # Output: [1, 3, 4, 5]
arr.remove(4)
print(arr) # Output: [1, 3, 5]
The length of an array
You can use the len()
function to get the length of an array, for example:
arr = [1, 2, 3, 4, 5] print(len(arr)) # Output: 5 <h2>Traversing Arrays</h2> <p>You can use the <code>for
loop to iterate over the elements in an array. For example:arr = [1, 2, 3, 4, 5] for num in arr: print(num)
Running result:
1 2 3 4 5
Array Slicing
You can use slicing to get a subarray of an array. For example:
arr = [1, 2, 3, 4, 5] print(arr[1:4]) # Output: [2, 3, 4] print(arr[:3]) # Output: [1, 2, 3] print(arr[2:]) # Output: [3, 4, 5]
Array Methods
In addition to the methods described above, arrays also have other commonly used methods, such as
pop()
,insert()
,index()
, andcount()
. These methods can perform various operations on arrays. Readers can refer to the official Python documentation for more details.Summary
This article introduces how to create, access, modify, delete, iterate, and slice arrays in Python. We hope that readers will quickly master the basics of Python arrays through this article. In actual development, flexible use of arrays can greatly improve code efficiency and readability.