Difference between revisions of "W1301 Arrays"

From Coder Merlin
m (Merlin moved page Project-1301 to W1301 Arrays: Improved navigation)
Line 81: Line 81:
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
     states.remove(at: 2)
     states.remove(at: 2)
</syntaxhighlight>
=== Python ===
''Note: Python does not have arrays; lists are used instead''
A list can be instantiated using a series of literals. For example:
<syntaxhighlight lang="python">
oddNumbers = [1, 3, 5, 7, 9, 11]
states = ["California", "Florida", "Texas"]
</syntaxhighlight>
An empty list can be instantiated:
<syntaxhighlight lang="python">
emptyArray = []
</syntaxhighlight>
The first element of a non-empty list is accessed using an '''index''' or '''subscript''' of 0. For example:
<syntaxhighlight lang="python">
firstState = states[0]
</syntaxhighlight>
One can determine if a list is empty by checking it's length:
<syntaxhighlight lang="python">
if len( states ) > 0:
    print("The array contains " + str(len(states)) + " states.")
</syntaxhighlight>
or by simply using <code>if</code>:
<syntaxhighlight lang="python">
if states:
    print("The array contains " + str(len(states)) + " states.")
</syntaxhighlight>
The last element of a list can be accessed by using <code>-1</code> as the index. The first element can be accessed by calling the negative length(e.g. <code>states[-len(states)]</code>)
<syntaxhighlight lang="swift">
print("The first state in the array is " + states[-len(states)])
print("The last state in the array is " + states[-1])
</syntaxhighlight>
We can use indices to iterate over each element at a specific location in a list with a for loop:
<syntaxhighlight lang="swift">
for i in range(0, len(states)):
    print(states[i])
</syntaxhighlight>
A very easy way to iterate over all ''elements'' in a list makes use of a '''for loop''':
<syntaxhighlight lang="swift">
for state in states:
    print("State: " + state)
</syntaxhighlight>
Adding a single element to the end of a list can be accomplished with '''append''':
<syntaxhighlight lang="swift">
states.append("New York")
</syntaxhighlight>
We can also '''insert''' an element at a specific index in the list:
<syntaxhighlight lang="swift">
states.insert(1,"New Jersey")
</syntaxhighlight>
This shifts the other elements in the list to “make room” for the new element.<br/>
Finally, elements can be removed with the '''del''' keyword:
<syntaxhighlight lang="swift">
del states[2]
</syntaxhighlight>
</syntaxhighlight>

Revision as of 17:11, 3 July 2019

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Prerequisites[edit]

Background[edit]

Overview[edit]

The Array Data Structure is a collection of elements each of which can be identified by an index. An array is stored so that the position of the element in memory (or other storage) can be easily calculated based only on the index. For example, consider an array of integers:

Array Data Structure


In this array, each integer requires thirty-two bits (or four bytes). Thus, there are four bytes from the beginning of each element to the beginning of the next element. This allows us to calculate the position of an integer in this array by adding the product of the element index (starting from zero) and the bytes required per element to the foundation address. In this case, the formula would be:

0x0800 + (3 * index)

Arrays are very common data structures and used in almost every program. CPUs generally enable assembly language programs to easily work with arrays. As an example, a base plus index mode enables a program to access an element by storing the foundation address in the base register and specifying the index (scaled by the size of each element) in the index register.

Properties[edit]

As an abstract data type, arrays are:

  • A collection type, meaning that a single variable conceptually “contains” many elements
  • Each item in the data structure is termed an element
  • The collection is ordered, that is, the order of the elements is maintained
  • Elements can be accessed randomly, that is, there is no need to access elements in any particular order
  • The array is homogenous, that is, all of the elements are of the same type


Swift[edit]

An array can be instantiated using a series of literals. For example:

   let oddNumbers = [1, 3, 5, 7, 9, 11]
   var states = ["California", "Florida", "Texas"]

An empty array can be instantiated by explicitly specifying its type:

    var emptyDoubleArray = [Double]()

The first element of a non-empty array is accessed using an index or subscript of 0. For example:

    let firstState = states[0]

One can determine if an array is empty using the isEmpty property and determine the number of items in the array using the count property:

    if !states.isEmpty {
        print("The array contains \(states.count) states.")
    }

A shortcut to access the first and last elements makes use of the first and last property which return a type of Element? (optional Element).

    print("The first state in the array is \(states.first!)")
    print("The last state in the array is \(states.last!)")

We can use indices to iterate over each element at a specific location in an array with a for loop:

    for index in 0 ..< states.count {
        print(states[index])
    }


A very easy way to iterate over all elements in an array makes use of a for loop:

    for state in states {
        print("State: \(state)")
    }

Adding a single element to the end of an array can be accomplished with append:

    states.append("New York")

We can also insert an element at a specific index in the array:

    states.insert("New Jersey", at:1)


This shifts the other elements in the array to “make room” for the new element.
Finally, elements can be removed with the remove method:

    states.remove(at: 2)

Python[edit]

Note: Python does not have arrays; lists are used instead

A list can be instantiated using a series of literals. For example:

oddNumbers = [1, 3, 5, 7, 9, 11]
states = ["California", "Florida", "Texas"]

An empty list can be instantiated:

emptyArray = []

The first element of a non-empty list is accessed using an index or subscript of 0. For example:

firstState = states[0]

One can determine if a list is empty by checking it's length:

if len( states ) > 0:
    print("The array contains " + str(len(states)) + " states.")

or by simply using if:

if states:
    print("The array contains " + str(len(states)) + " states.")


The last element of a list can be accessed by using -1 as the index. The first element can be accessed by calling the negative length(e.g. states[-len(states)])

print("The first state in the array is " + states[-len(states)])
print("The last state in the array is " + states[-1])

We can use indices to iterate over each element at a specific location in a list with a for loop:

for i in range(0, len(states)):
    print(states[i])


A very easy way to iterate over all elements in a list makes use of a for loop:

for state in states:
    print("State: " + state)

Adding a single element to the end of a list can be accomplished with append:

states.append("New York")

We can also insert an element at a specific index in the list:

states.insert(1,"New Jersey")


This shifts the other elements in the list to “make room” for the new element.
Finally, elements can be removed with the del keyword:

del states[2]