[go: up one dir, main page]

0% found this document useful (0 votes)
24 views33 pages

Array and List

The document explains the use of arrays in Python, highlighting their distinct nature compared to lists and Numpy arrays. It covers how to create, access, manipulate, and perform operations on arrays, including adding, changing, and removing elements. Additionally, it contrasts arrays with lists, emphasizing that arrays store homogeneous data while lists can hold heterogeneous data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views33 pages

Array and List

The document explains the use of arrays in Python, highlighting their distinct nature compared to lists and Numpy arrays. It covers how to create, access, manipulate, and perform operations on arrays, including adding, changing, and removing elements. Additionally, it contrasts arrays with lists, emphasizing that arrays store homogeneous data while lists can hold heterogeneous data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

ARRAYS AND LIST

WHY USE ARRAYS IN PYTHON?

Arrays in Python are Data Structures that can hold multiple


values of the same type. Often, they are misinterpreted as lists
or Numpy Arrays. Technically, Arrays in Python are distinct
from both these.

A combination of Arrays, together with Python could save you a


lot of time. As mentioned earlier, arrays help you reduce the
overall size of your code, while Python helps you get rid of
problematic syntax, unlike other languages.

For example: If you had to store integers from 1-100, you won’t
be able to remember 100 variable names explicitly, therefore,
you can save them easily using an array.
WHAT IS AN ARRAY IN PYTHON?

An array is basically a data structure which can hold more than one value
at a time. It is a collection or ordered series of elements of the same type.
Example:

a=arr.array('d',[1.2,1.3,2.3])

We can loop through the array items easily and fetch the required values
by just specifying the index number. Arrays are mutable(changeable) as
well, therefore, you can perform various manipulations as required.
CREATING AN ARRAY IN PYTHON:

Arrays in Python can be created after importing the array module as


follows –
→ import array as arr
The array(data type, value list) function takes two parameters, the first
being the data type of the value to be stored and the second is the value
list. The data type can be anything such as int, float, double, etc. Please
make a note that arr is the alias name and is for ease of use. You can
import without alias as well. There is another way to import the array
module which is –
→ from array import *
This means you want to import all functions from the array module.
CREATING AN ARRAY IN PYTHON
The following syntax is used to create an array.
Syntax:
a=arr.array(data type,value list)
#when you import using arr alias

OR
a=array(data type,value list)
#when you import using *

Example: a=arr.array( ‘d’ , [1.1 , 2.1 ,3.1] )


DATA TYPES AND THEIR CODES
ACCESSING ARRAY ELEMENTS IN PYTHON :

To access array elements, you need to specify the index


values. Indexing starts at 0 and not from 1. Hence, the index
number is always 1 less than the length of the array.
Syntax:
Array_name[index value]
Example:

a=arr.array( 'd', [1.1 , 2.1 ,3.1] )


a[1]

Output –
2.1
ACCESSING ARRAY ELEMENTS IN PYTHON :

import array as arr


a = arr.array('i', [2, 4, 6, 8])

print("First element:", a[0])


print("Second element:", a[1])
print("Last element:", a[-1])

Output
First element: 2
Second element: 4
Last element: 8
BASIC ARRAY OPERATIONS
FINDING THE LENGTH OF AN ARRAY

Length of an array is the number of elements that are actually present in an


array. You can make use of len() function to achieve this. The len()
function returns an integer value that is equal to the number of elements
present in that array.
Syntax:
→ len(array_name)
Example:

a=arr.array('d', [1.1 , 2.1 ,3.1] )


len(a)

Output – 3
This returns a value of 3 which is equal to the number of array elements.
ADDING/ CHANGING ELEMENTS OF AN ARRAY:
We can add value to an array by using the append(), extend() and
the insert (i,x) functions.
The append() function is used when we need to add a single element at the
end of the array.
Example:

a=arr.array('d', [1.1 , 2.1 ,3.1] )


a.append(3.4)
print(a)

Output –

array(‘d’, [1.1, 2.1, 3.1, 3.4])


The resultant array is the actual array with the new value added at the end
of it.
ADDING/ CHANGING ELEMENTS OF AN ARRAY:
To add more than one element, you can use the extend() function. This
function takes a list of elements as its parameter. The contents of this
list are the elements to be added to the array.
Example:

a=arr.array('d', [1.1 , 2.1 ,3.1] )


a.extend([4.5,6.3,6.8])
print(a)

Output –
array(‘d’, [1.1, 2.1, 3.1, 4.5, 6.3, 6.8])

The resulting array will contain all the 3 new elements added to the
end of the array.
ADDING/ CHANGING ELEMENTS OF AN ARRAY:
However, when you need to add a specific element at a particular
position in the array, the insert(i,x) function can be used. This
function inserts the element at the respective index in the array. It
takes 2 parameters where the first parameter is the index where
the element needs to be inserted and the second is the value.
Example:

a=arr.array('d', [1.1 , 2.1 ,3.1] )


a.insert(2,3.8)
print(a)
Output –
array(‘d’, [1.1, 2.1, 3.8, 3.1])
The resulting array contains the value 3.8 at the 3rd position in the
array.
ADDING/ CHANGING ELEMENTS OF AN ARRAY:
Arrays are mutable; their elements can be changed in a similar way as
lists.
import array as arr

numbers = arr.array('i', [1, 2, 3, 5, 7, 10])

# changing first element


numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])

# changing 3rd to 5th element


numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

Output
array('i', [0, 2, 3, 5, 7, 10])
array('i', [0, 2, 4, 6, 8, 10])
ARRAY CONCATENATION :
Any two arrays can be concatenated using the + symbol.
Example:

a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])


b=arr.array('d',[3.7,8.6])
c=arr.array('d')
c=a+b
print("Array c = ",c)

Output –
Array c= array(‘d’, [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
The resulting array c contains concatenated elements of arrays a and b.
SLICING AN ARRAY:

An array can be sliced using the : symbol. This returns a range of


elements that we have specified by the index numbers.
Example:

a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])


print(a[0:3])

Output –
array(‘d’, [1.1, 2.1, 3.1])
The result will be elements present at 1st, 2nd and 3rd position in the
array.
SLICING PYTHON ARRAYS

import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]


numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end

Output
array('i', [62, 5, 42])
array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])
REMOVING/ DELETING ELEMENTS OF AN ARRAY:
Array elements can be removed using pop() or remove() method. The
difference between these two functions is that the former returns the
deleted value whereas the latter does not.
The pop() function takes either no parameter or the index value as its
parameter. When no parameter is given, this function pops() the last
element and returns it. When you explicitly supply the index value, the
pop() function pops the required elements and returns it.
Example:

a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])


print(a.pop())
print(a.pop(3))

Output –
4.6
3.1
REMOVING/ DELETING ELEMENTS OF AN ARRAY:
The remove() function, on the other hand, is used to remove the value
where we do not need the removed value to be returned. This function
takes the element value itself as the parameter. If you give the index value
in the parameter slot, it will throw an error.
Example:

a=arr.array('d',[1.1 , 2.1 ,3.1])


a.remove(1.1)
print(a)

Output –
array(‘d’, [2.1,3.1])
The output is an array containing all elements except 1.1.
When you want a specific range of values from an array, you can slice the
array to return the same, as follows.
LOOPING THROUGH AN ARRAY
Example:
Output – a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
All values print("All values")
for x in a:
1.1
print(x)
2.2
print("specific values")
3.8
3.1 for x in a[1:3]:
3.7 print(x)
1.2
4.6
specific values
2.2
3.8

The above output shows the result using for loop. When we use for loop without any specific
parameters, the result contains all the elements of the array given one at a time. In the second
for loop, the result contains only the elements that are specified using the index values. Please
note that the result does not contain the value at index number 3.
SEARCHING AN ELEMENT IN AN ARRAY
import array

arr = array.array('i', [1, 2, 3, 1, 2, 5])

print ("The new created array is : ", end ="")

for i in range (0, 6):

print (arr[i], end =" ")

print ("\r")

# using index() to print index of 1st occurrence of 2

print ("The index of 1st occurrence of 2 is : ", end ="")

print (arr.index(2))

# using index() to print index of 1st occurrence of 1

print ("The index of 1st occurrence of 1 is : ", end ="")

print (arr.index(1))
ACTIVITY

Create a program that will accept values and search for numbers
with more than 1 occurrence. You have to show also the index where
they are located.
Validations for this program are necessary.
LISTS
ARRAYS AND LISTS

Arrays and lists are the same structure with one


difference. Lists allow heterogeneous data element
storage whereas Arrays allow only homogenous
elements to be stored within them.

If we needed to store a larger amount of variables of the


same type, we could easily solve this problem using a list.
We can imagine a list as a row of boxes, each of them
containing one item. The boxes are numbered by indexes,
the first one has an index of 0.
Generating lists with range()

Use the range() function and fill a list with numbers from 1 to 10. Since range
doesn't return a list but a general sequence, we'll have to convert it to list using the
list() function.

numbers = list(range(1, 11))

In order to print this list, we'll use the for loop

for number in numbers:


print(number, end = " ")
MODIFYING LIST ITEMS USING RANGE()
We only changed the values for the loop's variable, not the actual
list items. If we wanted to modify the list items in a loop, we'd have
to use item indexes to access them:

numbers = list(range(1, 11))


for i in range(len(numbers)):
numbers[i] += 1
print(numbers)

The result would be:

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]


STRING LISTS
simpsons = ["Homer", "Marge", "Bart", "Lisa", “Maggie”]

Aside from the range() function, we can also use the b to iterate through the list items.
The advantage to it is that we'd have both the item index and the item itself:

simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]


for i, item in enumerate(simpsons):
print("%d: %s" % (i, item))

The result:

0: Homer
1: Marge
2: Bart
3: Lisa
4: Maggie

Lists are often used to store intermediate results, which are used later in a program. If
we needed a result 10x, we would calculate it once and put it into a list. Then, we'd
simply read the result.
SLICING
It's also possible to get a slice of a list. The syntax is similar to accessing a list
item. However, we specify multiple arguments like in range() function.
Examples:

numbers = range(10)
print(list(numbers))
print(list(numbers[0:5]))
print(list(numbers[2:8]))
print(list(numbers[1:7:2]))
print(list(numbers[2:9:2]))

The result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[1, 3, 5]
[2, 4, 6, 8]
LIST METHODS

The append() method appends a new item at the end of a list.

The pop() method returns the last item in a list and removes the item from the list.

The insert () method inserts an item at a given position. The first parameter is the index and the second
one is the item to be inserted at this index.

The append () method appends all the items from a given sequence to the list.

The count () method returns how many occurrences of a given value are there in the list.

The clear () method removes all the items in the list. We can achieve the same behavior by writing del a[:].

The remove () method removes a given item from the list. Throws an exception if the element is not found.

The reverse () method reverses the elements in the list so the first element is at the last place and vice versa.
SORT()

As the name suggests, the method will sort our list. Its only parameter is the list
that we want to sort. It's so clever that it works according to what we have stored in
the list. Strings are sorted alphabetically, i.e. numbers depending on its value.

simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]


simpsons.sort()
for s in simpsons:
print(s, end = " ")

Output

Bart Homer Lisa Maggie Marge


INDEX()

The method returns the index of the first found item. The method takes an item as a
parameter. We can specify 2 additional numeric parameters indicating the start and the end
index of the searched area. Let's allow the user to enter the name of a Simpson's character and
tell them at what position he/she is stored.

simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]


simpson = input("Hello! What is your favorite character in the Simpsons, you may
only choose from the core family members: ")
if simpson in simpsons:
position = simpsons.index(simpson);
print("If I had to rank them, that would be no. %d on my list." % (position + 1));
else:
print("Hey! That's not a Simpson!")

Output:

Hello! What is your favorite character in the Simpsons (you may only choose from the
core family members): Homer
If I had to rank them, that would be no. 1 on my list!
LIST FUNCTIONS

Python also provides global functions for working with lists. They also work for any other type
of sequence.

len()
It returns the length of a list (the total number of items in it).

min(), max(), sum()


These are mathematical functions which return the smallest of the items (min()), the largest
item (max()), and the sum of all the items (sum()). The methods have no parameters. To easily
calculate the average of a list's items use the sum() and len() functions.

sorted()
This method does pretty much the same this as the sort() function, but it returns a sorted copy
of the original list without modifying the original one.

all()
Returns True if all the items are evaluated as True (non-zero numbers, non-empty strings, etc).
LIST FUNCTIONS
del()
any()
We can remove list items via so-called slicing:
Returns True if there is at least one
item evaluated as True (a non-zero
number, a non-empty string, etc): numbers = [1, 3, 2, 0, 5]
del numbers[1]
print(numbers)
list_1 = [1, 3, 2, 0, 5]
list_2 = [6, 4, 5, 1, 2]
list_3 = []
print(any(list_1)) The result:
print(any(list_2))
print(any(list_3)) Console application
[1, 2, 0, 5]

Alternatively:
The result:
numbers = [1, 3, 2, 0, 5]
True del numbers[1:3]
True print(numbers)
False
The result:

[1, 0, 5]

You might also like