pythonvariablesstring-lengthvariable-length-arrayvariable-length

In Python why does the variable specified inside the loop has length 1 whereas the other outside the loop has its original length?


As declaring a variable1 inside for loop I have assigned some string to it>>>whereas given another variable2 .....when provided with the output it shows variable1 len is 1 and variable2 has 8 how does that work???

    for variable1 in "something is here please help":
        print(variable1)
    variable2 = "abcdefgh"
    print(len(variable1))
    print(len(variable2))  

Solution

  • A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). In your case the sequence is a String( "something is here please help") and the iterator should go through all the letters: 's','o','m','t'... That's why its length is 1 which mean one single character. Please refer to: https://www.w3schools.com/python/python_for_loops.asp#:~:text=A%20for%20loop%20is%20used,other%20object%2Dorientated%20programming%20languages.