Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.10.3 Assigning a Value & Length of A List
Assigning a Value
- When creating the list: You can directly include values, like
[1, 2, 3]
, in most languages. - Add to an empty list: You can start with an empty list (
[]
) and then use methods likeappend()
orpush()
to add values to it. - Assign to specific positions: You can also assign values to specific positions in the list using an index, such as
myList[0] = 5
.
Javascript:
%%js
// Create a list with values
let myList = [10, 20, 30];
console.log(myList); // [10, 20, 30]
// Assign values to specific positions
let myList = [];
myList[0] = 5;
myList[1] = 15;
console.log(myList); // [5, 15]
// Append values
let myList = [];
myList.push(100);
myList.push(200);
console.log(myList); // [100, 200]
Python:
# Create a list with values
my_list = [10, 20, 30]
print(my_list) # [10, 20, 30]
# Assign values to specific positions
my_list = [0] * 3
my_list[0] = 5
print(my_list) # [5, 0, 0]
# Append values
my_list = []
my_list.append(100)
print(my_list) # [100]
Common Errors When Assigning
- Index Out of Range: Assigning a value to a non-existent index in the list.
- Example:
my_list[3] = 4
on a list with only three elements.
- Example:
- Incorrect Data Type: Assigning a value of an unexpected type.
- Example:
myArray[1] = "text"
in a numeric array.
- Example:
- Using
+=
Instead of=
: Misusing operators can lead to errors, especially with non-iterable types.- Example:
my_list += 5
on an integer variable.
- Example:
- Syntax Errors: Mistakes in syntax can prevent assignment.
- Example: Missing parentheses or brackets.
Length of a List
Javascript:
%%js
let myList = [10, 20, 30];
console.log(myList.length); // Output: 3
Python:
my_list = [10, 20, 30]
print(len(my_list)) # Output: 3