#18 Arrays / Python Lessons for Beginners

by Alex
#18 Arrays / Python Lessons for Beginners

Previous lesson: Lambda-functions Note: Python has no built-in support for arrays, but you can use Python lists instead. Arrays are used to store multiple values in a single variable:

cars = ["Ford", "Volvo", "BMW"]

What is an array?

An array is a special variable that can contain more than one value. If you have a list of items (for example, a list of car brands), storing cars in separate variables might look like this

car1 = "Ford";
car2 = "Volvo";
car3 = "BMW";

However, what if you wanted to jump through all the cars and find a specific one? What if you didn’t have 3 cars but 300? The solution is an array! An array can contain many values under one name, and you can also access the values by index.

Accessing the elements of an array

You refer to an element in an array by referring to the index. Get the value of the first element of the array:

x = cars[0]

Change the value of the first element of the array:

cars[0] = "Toyota"

Array length

Use the len() method to return the length of the array (the number of elements in the array). Print the number of elements in the cars array:

x = len(cars)

Note: The length of an array is always greater than the index of the last element.

Array element loops

You can use a for loop to loop through all the elements of an array. Let’s derive each element from the cars loop:

for x in cars:
print(x)

Output:

Ford
Volvo
BMW

Adding array elements

You can use the append() method to add elements to the array. Let’s add one more element to the cars array:

cars.append("Honda")

Deleting elements of an array

Use the pop() method to remove elements from the array. Delete the second element from the cars array:

cars.pop(1)

You can also use the remove() method to remove an element of the array. Delete the element with the value “Volvo”:

cars.remove("Volvo")

Note: The remove() method removes only the first occurrence of the specified value.

Array Methods

Python has a set of built-in methods that you can use when working with lists/arrays. Method Valuearend()Adds items to the end of the listclear()Removes all items in the listcoru()Returns a copy of the listcount()Returns the number of items with a specific valueexcluded()Adds list items to the end of the current listinԁex()Returns the index of the first item with a specific valueinnsert()Adds an item to a specific positionror()Removes an item by indexremove()Removes items by valueverse()Upsets the order in the listsort()Sorts the list Note: Python has no built-in support for arrays, you can use Python List instead. Next: Python classes and objects

Related Posts

LEAVE A COMMENT