Lists
Lists
List• A list is a consecutive group of mutable memory locations.
• Each element can be a different type
• Each individual value in an list is referred to as an element.
• The position number is more formally called a subscript or index.• Subscripts must be an integer• Can use an expression as an index.
• The first element in every kist has subscript 0 (zero) and is sometimes called the zeroth element.
• To refer to a particular location or element in the list, specify the name of the list and the index of the particular element.
• The size of an list is how many elements in the list, denoted by n.
• The highest subscript in an list is n - 1.
Checkpoint:•1. What is the size of an array?
•2. What is the range of indices of an array?
Refer to the following array:int age[] = {10, 11, 18, 13, 13, 16, 41, 12};
•3. What is in the 7th position in the array?
•4. What element is storing the value 12?
List Initializer
•To create and initialize a list is similar to a variable declaration only with multiple elements instead od a single one:
Code: listName = [ele1, ele2, …]
Ex. ▫names = [“Frankenstein”, Werewolf”,
“Boogeyman”]▫ages = [18, 18, 21, 21, 21, 22, 35, 38, 32, 36]▫Combo=[23, “Cake”, “Cupcakes”, 34]
Traversing an Array• In order to access each element of an array we
must hard code each statement which can take up lots of code.
• Also if we are trying to program in the general if we add an extra element we have to change all of our code
▫Question: How could we traverse or iterate through this list more efficiently?
VS
Reasons traversing an array with a for loop helps with programming in the general•Updating•Mathematical operations ( ie. Summing)•Printing •Searching•Testing
Common List Functions
Declaring Lists Lists are dynamic data structures
To declare a list when not initializing:○ Code: listName =[]
The interpreter reserves memory as it is needed. In order to add an item to a List use the append
function. Code: listName.append(value)
Note: Add element vs. update element
Other List Functions