How do we retrieve an element at a specific place from a list or a string? For example, to get the second element from the list a = [1, 2, 3], what code would I write? →
Indexes
What are some attributes of list and string indexes? That is… when you index into a sequence type…
What date type does the index have to be? →
Are list indexes sequential and consecutive, or are they unordered? →
Generating a Sequence of Integers
One way of iterating over every item in a list or a string is to go through each element by indexing.
…But how would you generate all of those indexes and go through each one? →
Hint: there are two ways to do this using constructs / statements that we've used before.
for loop with range
while loops
For Loops and Indexes
Use a for loop to print out every element in the list a = ["quill", "qat", "quip"]: →
Some hints:
what parameters should be passed to range?
what's the start index?
what's the last index?
how do you access a list element?
While Loops and Indexes
Use a while loop to print out every element in the list a = ["quill", "qat", "quip"]: →
Some hints:
what index do you start with?
what's the end condition?
how do you access a list element?
The "Usual" Way
Finally, to round things out, use a for loop - without indexes - to print out every element in the list a = ["quill", "qat", "quip"]: →
Incrementing Every Element
Let's try adding one to every element in a list.
Start with the following list of numbers: numbers = [9, 19, 29, 39]
We could do something like this:
Incrementing Every Element Continued
But, of course, it would be better if we didn't have to manually re-assign every index explicitly. Maybe we can…
go over every element using indexes generated by range
increment each number by one by using assignment!
Reversing a List
Write a function that takes a list as an input and returns the list in reverse order (btw, there's already a list method that does this) →
Another (More Destructive Way) to Reverse a List
Can you use pop to do it? →
But Wait - What Happened?
What's the output of the pop() version of the solution? →
Iterating with Indexes vs Regular Iteration
How do you know which kind of loop to use when both loops (using indexes vs using elements) seem pretty similar? →
If using an index is necessary… use the for i in range version. For example, some situations may be: