Introduction to Arrays
Sue Inn Chng
The University of Sydney https://www.toxel.com/inspiration/2012/04/26/lego-cartoon-characters/ Page 1 https://www.turbosquid.com/3d-models/lego-bricks-2×2-3d-model-1491947
Image credit:
Copyright By PowCoder代写 加微信 powcoder
Data Types
Basic (Single Value)
– Integers
– Floating Points – Boolean
– Characters
Containers (Multiple Values)
– Dictionaries
The University of 2
Recap: strings
– A string of characters only make sense when they are together.
– A string variable contains the memory address that contains all characters.
– We can access each character (element or item) in a string variable by referring to its index. See this Ed Lesson on Week 5.
The University of 3
Zero-based Indexing and One-based Indexing
– Thereareprogramminglanguagesthatuseone-based indexing. The first element starts at one instead of zero.
– Consequences:
• See Slide 11, Lecture 5a.
• Index-1: Index of last element is the same as total number of elements.
• Index-0: Index of last element is one less than the total number of elements.
The University of 4
Array – What and Why?
– Adatastructureisawaytoorganizedatathatwewishto process with a computer program.
– An array is a contiguous block of memory containing multiple values of the same type.
– Arraysolvestheproblemofhavingmanyvariables.
– Astringisconsideredanarrayofcharactersinsome
programming languages like C.
The University of 5
– A race requires TWO(2) participants to run around the track FIVE(5) times.
– How do you record the total time taken by each participant to run around the track IRL?
– Whatifitisnowamarathonwithat least 50 participants?
– Canyouseethebenefitofstoring data as a group?
The University of
Image credit: Clipartmax – Race Clipart Flag Png Page 6
Python Collections
– Python documentation: list, tuples, set, dictionary
– Fundamental operations: – Initialize,
– Modify elements (if possible)
The University of 7
Arrays and Python List
– Amulti-elementarrayisdefinedascommaseparatedobjects of the same type (homogenous) within the square brackets [ and ].
– Python’slistisNOTthesameasarrays,i.e. arrays != lists
– Thesedifferenceswillbeimportantwhenlearninganew programming language e.g. C.
– Scientific calculations are often performed on numpy arrays in Python instead of lists.
The University of 8
Initialization
– Many ways to initialize list:
– Reference: https://docs.python.org/3/library/stdtypes.html#lists
– Can you spot examples of each initialization below?
– Go to Ed Lesson. Run demo.py. The University of 9
len() function
– You can access the length of an array (total number of elements) using Python’s built-in function len()which returns the number of elements.
– Important: Python is zero-based indexing, the last element of an array is always: len() – 1
– With knowledge of the length of an array, you can easily access (and manipulate) the values in the array using loops.
– Go to Ed Lesson and try it out. How many elements are there present in each list variable?
The University of 10
Accessing Elements and Slicing
– The first element of an array in Python starts at 0.
– Can you identify the index for the values Joshua?
– What values does these slices return?
– tutors[1:2] – tutors[:2] – tutors[2:]
The University of 11
– Did you know we can do the same operations on tuples?
– GotoEdLesson.Rundemo.py.
– Whatdatatypearevariables:obj_in_garageand ls_objs ?
– How many elements are there in these variables?
– Canyouworkoutthevaluesstoredattheselocations: – obj_in_garage[1]?
– ls_objs[0]?
Draw the object level trace diagram to explain your answer. The University of 12
Checkpoint: Initialization and Accessing Elements
– Thefirstelementisalways0.
– Thelen()functionwillreturnthetotalnumberofelementsin
the collection.
– Functioncallsarealwaysinthisformat:function_name(
– Accessingelementsinatuplefollowsthesamesyntaxas accessing elements in a list e.g. tuple_name[index].
– GotoEdLesson.
The University of 13
Mutable and Immutable
– List and tuples have common operations:
– Length using len(empty_ls)
– Accessing ith item of s from origin 0 e.g. tutors[1]
– Slices from index i to j-1 e.g. tutors[1:2]
– Listsaremutable.Tuplesareimmutable.
– Youcanmodifylists’elementsaftercreation.
– Likestringobjects,onceyoucreateatuple,youcannotmodifyitselements.
– Tuplesareusedtopassmultiplevaluesoutafunctiontoreducetheriskof modifying the function’s return values.
– Goto: EdLesson.Rundemo.py. The University of 14
Did you notice?
– We can assign a new value to an existing list element using the assignment operator but not to a tuple.
• final_list[2] = “Luis” # uh-oh • tutors[2] = “Luis” # ok!
– We can append new values to an existing list:
• + operator e.g. tutors = tutors + more
• append method e.g. tutors.append(“name”)
– Implications:
• Once tuples are created, they cannot be modified.
• Adding two list of integers will not add the integers within together.
• Adding two tuple of integers will create a new tuple concatenating both tuples contents.
• Recommendation: numpy for scientific and engineering applications. Run lotto.py
The University of 15
Function – Iterating through elements
– Programmingidioms–patternsthatyouusetosolvedifferent problems e.g. iterating through a string object is conceptually the same as iterating through the elements of a list.
– Goto:EdLessonandhaveago.
– ThisquestionisverysimilartoEchoAgain2.0.
– Maindifference:
– Itisencapsulatedinafunctionwhichreturnsastringobjectandhas
arguments of either list, tuple or string object.
– Thefunctiondoesnotdisplayanythingtotheterminal.
– What other idioms have you encountered? The University of 16
– Arraysarecontiguousblocksofmemory.
– Wecaneasilyaccess(andmanipulate)agroupofrelated
– You can have arrays of anything. As the programmer, you are deciding what memory you need to have and then how it is processed.
– You can mix different type of objects into the same array in Python but this may not work in the other languages. It is best that you use the same type of objects in your array.
The University of 17
Reading This Week
– Chapter10.Lists.Downey,A.B.(2015).ThinkPython:Howto Think Like a Computer Scientist (2e ed.). O’ , Incorporated.
– Chapter12.Tuples.Downey,A.B.(2015).ThinkPython:How to Think Like a Computer Scientist (2e ed.). O’ , Incorporated.
The University of 18
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com