Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Big Idea 3.10 Part 2
Learn more about lists
Part 1 | Part 2 | Part 3 | Part 4 |
Creating a list
# Python
# Creating an empty list
aList = []
# Creating a list with elements
aList = [1, 2, 3, 'apple', 'banana']
%%js
// Javascript
// Creating an empty array
let aList = [];
// Creating an array with elements
aList = [1, 2, 3, 'apple', 'banana'];
Accessing Elements
You can access an element at a specific index using the syntax aList[i]
. Remember, the first element is at index 0
.
# Python
aList = ['apple', 'banana', 'cherry']
print(aList[0]) # Output: 'apple'
%%js
// Javascript
const aList = ['apple', 'banana', 'cherry'];
const firstElement = aList[0]; // apple
const secondElement = aList[1]; // banana
Appending Elements
Use the append()
method to add an element to the end of the list.
# Python
aList.append('grape') # Adds 'grape' at the end
print(aList) # Output: ['apple', 'banana', 'cherry', 'kiwi', 'grape']
%%js
// Javascript
let aList = ['apple', 'banana', 'cherry', 'kiwi'];
// Adding 'grape' at the end
aList.push('grape');
// Printing the array
console.log(aList); // Output: ['apple', 'banana', 'cherry', 'kiwi', 'grape']