Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Big Idea 3.10 Part 4
Learn more about lists
Part 1 | Part 2 | Part 3 | Part 4 |
Modifying Elements
# Python
aList = ['apple', 'banana', 'cherry']
aList[1] = 'kiwi' # Change 'banana' to 'kiwi'
print(aList) # Output: ['apple', 'kiwi', 'cherry']
%%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
# Python
aList = ['apple', 'banana', 'cherry']
number_of_elements = len(aList) # Gets the number of elements
print(number_of_elements) # Output: 3
%%js
// Javascript
let aList = ['apple', 'banana', 'cherry'];
let numberOfElements = aList.length; // Gets the number of elements
console.log(numberOfElements); // Output: 3
Interating through a List
# Python
for item in my_list:
{ <block of statement> }
%%js
// Javascript
let myList = ['apple', 'banana', 'cherry'];
for (let item of myList) {
// Replace this comment with your block of statements
console.log(item); // Example statement
}
Hacks
- Create a list and try adding and deleting different elements
- Find the sum of even numbers in a list