There is no built-in support for arrays in Python, but you can use Python lists instead
Arrays are used to store multiple values in a single variable :
Create an array containing car brands:
cars = ["Porsche", "Volvo", "BMW"]
An array is a special variable that can contain multiple values at one time.
If we had a list of items (for example, a list of car brands), storing the brands in a single variable might look like this:
car1 = "Porsche" car2 = "Volvo" car3 = "BMW"
However, if we needed to loop through the brands to find a specific car brand, what should I do? What if there are not only 3 cars, but 300 cars?
The solution is arrays!
Arrays can hold multiple values under a single name, and we can access these values by referencing the index number.
Reference array elements by index number. Get the value of the first array item:
x = cars[0]
Modify the value of the first array item:
cars[0] = "Audi"
Use the len()
method to Returns the length of the array (the number of elements in the array).
Return the number of elements in the cars array:
x = len(cars)
Note:
The array length is always one greater than the highest array index.
We can use for in
to loop through all elements of the array.
Print each item in the cars array:
for x in cars: print(x)
We can use the append()
method to add elements to the array . Adding one more element to the cars array:
cars.append("Audi")
We can use the pop()
method to remove an element from the array. Delete the second element of the cars array:
cars.pop(1)
We can also use the remove()
method to remove elements from the array. Remove elements with value "Volvo":
cars.remove("Volvo")
Note
: The remove()
method of a list only removes the first occurrence of the specified value.
数组方法 Python 提供一组可以在列表或数组上使用的内建方法。 append() 在列表的末尾添加一个元素 clear() 删除列表中的所有元素 copy() 返回列表的副本 count() 返回具有指定值的元素数量。 extend() 将列表元素(或任何可迭代的元素)添加到当前列表的末尾 index() 返回具有指定值的第一个元素的索引 insert() 在指定位置添加元素 pop() 删除指定位置的元素 remove() 删除具有指定值的项目 reverse() 颠倒列表的顺序 sort() 对列表进行排序
Tips: Python does not have built-in support for arrays, but you can use Python lists instead.
The above is the detailed content of What is Python's array and how to use it. For more information, please follow other related articles on the PHP Chinese website!