Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Big Idea 3.10 Part 3- Modifying Lists
Learn more about how to modify lists and check their length!
Modifying Elements
Since lists in Python are zero-indexed, meaning the first element is at index 0
, the second at index 1
, etc, here, aList[1]
refers to the second element, which is 'banana'
. This line updates that element to 'kiwi'
.
# Python
aList = ['apple', 'banana', 'cherry']
aList[1] = 'kiwi' # Change 'banana' to 'kiwi'
print(aList) # Output: ['apple', 'kiwi', 'cherry']
Here, the index is set to 2, which corresponds to the third element of the array, 'cherry'
. Then, the value is updated at the specified index (2) from 'cherry'
to 'kiwi'
.
%%js
// Javascript
let alist = ['apple', 'banana', 'cherry', 'grape'];
// Specify the index you want to update
let index = 2; // For example, to update 'cherry'
// Update the value at the specified index
alist[index] = 'kiwi'; // Now 'cherry' is replaced with 'kiwi'
console.log(alist); // Output: ['apple', 'banana', 'kiwi', 'grape']
Checking Length
The len()
function is a built-in Python function that returns the number of items in an object, in this case, the list aList. Since aList contains four elements, len(aList)
will return 4. This value is then stored in the variable number_of_elements
.
# Python
aList = ['apple', 'banana', 'kiwi', 'grape']
number_of_elements = len(aList) # Gets the number of elements
print(number_of_elements) # Output: 4
The .length
property of the list is used to determine the number of items in aList.
%%js
// Javascript
let aList = ['apple', 'banana', 'kiwi', 'grape'];
let numberOfElements = aList.length; // Gets the number of elements
console.log(numberOfElements); // Output: 4
Iterating through a List
Iterating a list means going through each element of the list one by one, allowing you to perform operations or access the elements sequentially. This line starts a for
loop that iterates over each element in the fruit
list. The variable fruit
will take on the value of each element in the list, one at a time.
# Python
aList = ['apple', 'banana', 'cherry']
for fruit in aList:
print(fruit) # Output: apple, banana, cherry
%%js
// Javascript
let aList = ['apple', 'banana', 'cherry'];
for (let fruit of aList) {
// Replace this comment with your block of statements
console.log(fruit); // Example statement
}
Popcorn Hack
- Try changing one of your elements into something new