Assigning a Value

  • To assign values to a list, you can either create the list with initial elements or add items to an existing list.

    1. When creating the list: You can directly include values, like [1, 2, 3], in most languages.
    2. Add to an empty list: You can start with an empty list ([]) and then use methods like append() or push() to add values to it.
    3. 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

    1. 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.
    2. Incorrect Data Type: Assigning a value of an unexpected type.
      • Example: myArray[1] = "text" in a numeric array.
    3. Using += Instead of =: Misusing operators can lead to errors, especially with non-iterable types.
      • Example: my_list += 5 on an integer variable.
    4. Syntax Errors: Mistakes in syntax can prevent assignment.
      • Example: Missing parentheses or brackets.


    Length of a List

  • To get the length of a list (i.e., the number of elements it contains), you can use:
  • JavaScript: .length
  • Python: len()
  • These methods return the total number of elements in the 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
    
    

    Popcorn Hack: Assigning Values to a List and Finding Its Length

    Create a list of your five favorite foods.

    Add two more items to your list using the .push() method.

    Find and print the total number of items in the list using .length