Lab 12
Lab 12
Arrays
Arrays are used to store multiple values in one single variable:
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
['Ford', 'Volvo', 'BMW']
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by
referring to an index number.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead.
Tasks
• Write a Python program to reverse the order of the items in the array.
OUTPUT :
Original array: [1, 2, 3, 4, 5]
Reversed array: [5, 4, 3, 2, 1]
Explanation :
Array Definition:
➢In Python, an array is usually represented as a
list. We start by defining a list called arr that
contains five numbers: [1, 2, 3, 4, 5].
Slicing for Reversing:
➢The key part of reversing the array is using
slicing with the notation [::-1].
Here's how it works:
➢The general syntax for slicing is
arr[start:end:step].
➢start specifies the index where to begin, end
specifies where to stop, and step controls how
the elements are accessed.
➢When start and end are omitted and step is set
to -1, the entire array is traversed backward,
effectively reversing it.
CODE :
# Define the array (or list)
arr = [1, 2, 3, 2, 4, 2, 5]
OUTPUT :
Explanation
Array Definition:
We start by defining a list called arr. In this
example, the list is [1, 2, 3, 2, 4, 2, 5], which
contains the number 2 multiple times.