Arrays - Programming Techniques
Document Details
Uploaded by MiraculousCyan
Tags
Summary
This document provides an introduction to arrays in programming, specifically concentrating on Python. It covers various aspects of working with arrays, including creating, accessing, updating, and manipulating entries. A concise explanation of different aspects of array management are displayed.
Full Transcript
2.2 Programming Techniques Arrays Start print ("What is your SELECT * FROM name") Objectives You will apply: The use of the three basic programming constructs used to cont...
2.2 Programming Techniques Arrays Start print ("What is your SELECT * FROM name") Objectives You will apply: The use of the three basic programming constructs used to control the flow of a program: Sequence Selection Iteration (count- and condition-controlled loops) The use of arrays (or equivalent) when solving problems, including both one-dimensional (1D) and two-dimensional arrays (2D) Contents 1.Introduction to arrays 2.Creating, accessing and updating arrays 3.Adding and removing elements from arrays 4.Counting the length of arrays using the len() function 5.Slicing the elements in an array using the slice() function 6.Other array functions 7.Using user input in array functions 8.Printing the elements of arrays Introduction to arrays Discussion Why is this code inefficient? highscore1=125 highscore2=63 highscore3=75 highscore4=120 highscore5=120 highscore6=71 highscore7=94 highscore8=100 Using many variables is a long-winded and inefficient approach. Comparison Creating variables and arrays VARIABLES ARRAYS A variable stores one value. An array stores multiple values under a single name. Each value within the array is an element. EXAMPLE 1: EXAMPLE 1: highscores = [125,63,35,12] highscore1 = 125 4 variables have been replaced highscore2 = 63 by one array with 4 elements. highscore3 = 35 highscore4 = 12 EXAMPLE 2: EXAMPLE 2: names = ["John","Julie","Ahmed"] name1="John" 3 variables have been replaced name2="Julie" by one array with 3 elements. name3="Ahmed" Creating, accessing and updating arrays Information Creating arrays To create an array, the identifier is followed by the equals symbol and then open and closed square brackets. If the array is to be created with elements, they are written in between the square brackets, separated by commas. This is optional as an empty array can be created where elements are added later. SYNTAX: array_name = [element 1, element 2, element 3, etc.] EXAMPLES: An empty highscores = [] array. An array with 4 integer highscores = [125,63,35,12] elements. An array with 3 string names = ["John", "Pablo", "Jessica"] elements. NOTE: If the elements in an array are strings, they must be enclosed within quotation marks (like variables). Information Accessing values in arrays Each element in an array has an index, like strings. The index of each element points to its position in the array. To refer to a particular element in an array, the name of the array is written followed by the index between square brackets: SYNTAX: array_name [index] The index is used to: Print elements. Update existing elements. Insert elements. Remove elements (using the pop() function). Information Indexing The index of arrays generally starts at zero or one. Most programming languages (e.g. Python, C, Java, etc.) start at zero; some programming languages start at one (e.g. Fortran, Cobol, etc.); and some give you the choice between the two (e.g. Julia, etc.). An array where the index starts at zero is called a zero-indexed array or a zero-based array. An array where the index starts at one is called a one-indexed array or a one-based array. Important Accessing elements in arrays – example 1 EXAMPLE: ages array ages = [125,63,35,19,56] Index 0 1 2 3 4 Eleme 125 63 35 19 56 nt To access element 125: ages[0 ] To access element 63: ages[1 ] To access element 35: ages[2 ] Important Accessing elements in arrays – example 2 EXAMPLE: names array names = ["John", "Pablo", "Jessica", "Hamza", "Xi","Jack", "Gianluca"] Index 0 1 2 3 4 5 6 Eleme John Pablo Jessica Hamza Xi Jack Gianluc nt a To access element "John":names[ 0] To access element "Gianluca": names[ 6] To access element "Hamza": names[ 3] Comparison Printing variables and arrays VARIABLES ARRAYS Each variable has to be printed Each element can be printed individually: individually using the index: print(highscore1) print(highscores) print(highscore2) print(highscores) print(highscores) print(highscore3) print(highscores) print(highscore4) All the elements in the array can also be printed: print(highscores) There are more effective ways of doing this which will be looked at later. Information Updating the elements in arrays The elements in an array can be updated using the index. SYNTAX: array_name [index] = new_value EXAMPLES: highscores = [125,63,35,12] An array has been created with 4 elements. highscores = 400 The 125 at index 0 has been updated to 400. highscores = 50 The 35 at index 2 has been updated to 50. What values will be printed? print (highscores )40 0 print (highscores )63 print (highscores )50 Discussion What is wrong with the following program? highscores = [125,63,35,12] highscores = 8 print(highscores) An element at index 4 is being updated (highscores = 8), however the index does not exist as the highscores array only has 4 elements [Indexes 0, 1, 2 and 3]. It will thus produce an error message when the program is run: Adding and removing elements from arrays The following functions can be used to add elements to arrays: Append() Extend() Insert() The following functions can be used to remove elements from arrays: Remove() Pop() Clear() Information Adding an element using the append() function The append() function is used to add a single element to the end of an array. SYNTAX: array_name.append(element) Ind Eleme ex nt EXAMPLE 1: 0 Renaul cars = ["Renault","Ford","VW"] t cars.append("BMW") 1 Ford The car BMW has been added to index 3. 2 VW 3 Ind BMW Eleme EXAMPLE 2: results = [30,32] ex nt results.append(15) 0 30 The result 15 has been added to 1 32 index 2. 2 15 Information Adding an element using the extend() function The extend() function is used to add multiple elements to the end of an array. SYNTAX: array_name.extend([element1, element2, element3, etc.]) EXAMPLE: cars = ["Renault","Ford","VW"] cars.extend(["BMW","Nissan","Kia"]) Ind Eleme ex nt 0 Renaul t The cars BMW, 1 Ford Nissan and Kia have 2 VW been added to 3 BMW index 3, 4 and 5 respectively. 4 Nissan 5 Kia Information Inserting an element using the insert() function The insert() function inserts the specified element at the specified position. It has two parameters: The index in which to insert the value. The element to be inserted. SYNTAX: array_name.insert(index, element) EXAMPLE: highscores = [125,63,70,120] Ind Eleme highscores.insert(2,150) ex nt 0 125 The integer 150 has been inserted 1 63 into index 2. 2 150 3 70 4 120 Information Removing elements using the remove() function The remove() function is used to remove an element from an array. The element being removed must be specified. If there are multiple occurrences of the same element, only the first occurrence is removed. SYNTAX: array_name.remove(element) Ind Eleme EXAMPLE: ex nt The element 125 will be ages = [125,63,35] 0 125 removed. ages.remove(125) 1 63 2 35 Information Removing elements using the pop() function The pop() function is also used to remove an element from an array. The index of the element being removed must be specified. SYNTAX: array_name.pop(index) EXAMPLE: names = ["John", "Sam", "Ali"] names.pop(1) Ind Eleme ex nt 0 John It will remove the element 1 Sam "Sam". 2 Ali Information Removing all elements from arrays using the clear() function The clear() function removes all the elements from an array. SYNTAX: array_name.clear() EXAMPLES: highscores = [125,63,35,12] highscores.clear() Removes all elements (125, 63, 35 and 12) from the array. Counting the length of arrays using the len() function Information Counting the length of arrays using the len() function The len() function is used to count the number of elements in an array. SYNTAX: len(array_name) EXAMPLE: This can be combined with the print() function to output the number of elements in the array. highscores = [125,63,35,12] print (len(highscores)) 4 There are 4 elements in the array so 4 is printed to the screen. Slicing the elements in an array using the slice() function Information Slicing the elements in an array using the slice() function The slice() function is used to return a specific range of elements from an array. It does not modify the original array. It uses the same parameters that are used to slice a string. SYNTAX: array_name[slice(start , stop , step)] EXAMPLE 1: highscores = [125,63,70,120] print (highscores[slice(1,3)]) [63, The elements in index 1 and 2 are sliced 70] and printed. EXAMPLE 2: names = ["John","Sam","Vijay","Roberto","Sally","Hasan"] print (names[slice(2,5)]) The elements in index 2, ['Vijay', 'Roberto', 3 and 4 are sliced and 'Sally'] printed. Other array functions Information Other array functions There are other functions which can be used on arrays. Some of these are summarised below. Function What it does Syntax reverse() Reverses the elements in array_name.reverse() an array. sort() Sorts an array into array_name.sort () ascending order. count() Returns the number of occurrences of an element array_name.count(value) in an array. min() Returns the minimum value min(array_name) in the array. * max() Returns the maximum value max(array_name) in the array. * *If the values are strings, an alphabetically Using user input in array functions Information Using user input in array functions User input can be used in functions to carry out operations on arrays. The following example shows how this works when removing elements from an array, however, this can also be applied to other array functions (e.g. append, insert, etc.). EXAMPLE: Removing elements from an array based on user input The user inputs the element they want to be highscores = [125,63,35] removed from the highscores array. It is choice= int(input("Enter a highscore to remove:")) stored in the variable named choice. highscores.remove(choice) Usually, the element that is to be removed is inserted between the brackets (e.g. 125, 63, etc.). However, it is also possible to insert a variable (the variable choice in this example) so that the element that is specified by Comparison Comparing appending methods Normal method User inputted method ages = [125,63,35] ages = [125,63,35] choice= int(input("Enter an age:")) An extra line is included which asks the user to input an age which is stored in the variable choice. ages.append(5) The element 5 will always be ages.append(choice) The value stored in the variable appended to the ages array. choice is appended to the ages array. Printing the elements of arrays Information Printing the elements of arrays This can be achieved by writing the name of the array within the print() function. The output is not presentable highscores = [125,63,35,12] [125, 63, 35, as the elements are printed print(highscores) 12] within brackets and separated by commas. The brackets and commas can be removed by adding an asterisk * before the name of the array: 125 63 35 The previous example has been highscores = [125,63,35,12] 12 improved, however, it is difficult print(*highscores) to distinguish between the different elements as they are on Each element can be printed on a newthe same line by line. the separator using 12 parameter: 5 highscores = [125,63,35,12] 63 print(*highscores,sep="\n") 35 12 The elements in an array can also be printed using a for loop (to be