Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Big Idea 3.10 Part 3
Learn more about lists
Part 1 | Part 2 | Part 3 | Part 4 |
Inserting Elements
# Python
alist = ['apple', 'banana', 'cherry']
alist.insert('apple', 'a') # alist is now ['apple', 'a', 'banana', 'cherry']
%%js
// Javascript
let alist = ['apple', 'banana', 'cherry'];
// Find the index of 'apple'
const index = alist.indexOf('apple');
// Insert 'a' before 'apple'
if (index !== -1) {
alist.splice(index, 0, 'a'); // 0 indicates no elements to remove
}
console.log(alist); // Output: ['a', 'apple', 'banana', 'cherry']
Removing Elements
# Python
aList.remove('kiwi') # Removes 'kiwi' from the list
print(aList) # Output: ['apple', 'banana', 'cherry', 'grape']
%%js
// Javascript
let aList = ['apple', 'banana', 'cherry', 'kiwi', 'grape']; // Find the index of 'kiwi'
if (index !== -1) {
aList.splice(index, 1); // Removes 'kiwi' from the list
}
console.log(aList); // Output: ['apple', 'banana', 'cherry', 'grape']
Deleting an element
You can use the del
statement to remove an item at a specific index.
# Python
del aList[2] # Deletes 'cherry' at index 2
print(aList) # Output: ['apple', 'banana', 'grape']
%%js
// Javascript
let aList = ['apple', 'banana', 'cherry', 'grape'];
// Delete the element at index 2
aList.splice(2, 1); // Removes 1 element at index 2
console.log(aList); // Output: ['apple', 'banana', 'grape']