Array and List
Array and List
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:
OR
a=array(data type,value list)
#when you import using *
Output –
2.1
ACCESSING ARRAY ELEMENTS IN PYTHON :
Output
First element: 2
Second element: 4
Last element: 8
BASIC ARRAY OPERATIONS
FINDING THE LENGTH OF AN ARRAY
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:
Output –
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:
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:
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:
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
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:
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:
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
print ("\r")
print (arr.index(2))
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
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.
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:
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 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.
Output
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.
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).
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]