🔄

Input a List Using Loops in Python

Jul 15, 2024

Input a List Using Loops in Python

Key Topics Covered

  • Problem with the Input Method
  • Input a List Using Loops

Problem with the Input Method

  • Issue: input() always returns user input as a string.
  • Example:
    • When asking for a list of numbers: numbers = input("Enter a list of numbers")
    • User enters: "67 48 90"
    • Problem: Treated as a single string, not separate list items.

Visual Example

  • Expected: [67, 48, 90] (with indices 0, 1, 2)
  • Actual: ['6', '7', ' ', '4', '8', ' ', '9', '0'] (8-character string list)

Input a List Using Loops

Steps and Commands

  1. Receive the Number of Elements

    n = int(input("Enter the number of elements"))
    • Input is typecast to an integer.
  2. Create an Empty List

    numbers = []
  3. Use a For Loop to Receive Individual Items

    for i in range(n): x = int(input()) numbers.append(x)
    • **Details: **
      • range(n): Loop runs n times.
      • int(input()): Typecast input to integer and store in x.
      • numbers.append(x): Add x to the numbers list.

Example Walkthrough

  1. Prompt and Receive Number of Elements

    • User enters: 3
    • n now points to 3 (integer).
  2. Create Empty List

    • Command: numbers = []
  3. For Loop Execution

    • Loop runs 3 times (0 to 2).
    • **First Iteration: **
      • User input: 67
      • x points to 67
      • numbers.append(x) adds 67 to numbers list. List now: [67].
    • Second Iteration:
      • User input: 48
      • x points to 48
      • numbers.append(x) adds 48 to numbers. List now: [67, 48].
    • Third Iteration:
      • User input: 90
      • x points to 90
      • numbers.append(x) adds 90 to numbers. List now: [67, 48, 90].
  4. Check the Final List

    print(numbers)
    • Output: [67, 48, 90]

Conclusion

  • Successfully input a list of numbers using loops.
  • Able to handle each element separately and store in a list as integers.