-1

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))  
  • `variable1` is used to iterate over a string, so it holds one character at a time. You never assign any long string to `variable1`. – deceze Apr 09 '21 at 20:29

1 Answers1

0

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.

  • Note that there are infinitely more kinds of iterables than just lists, tuples, dicts, sets and strings. – deceze Apr 09 '21 at 20:44
  • Any custom class you write can be made iterable, that alone allows for infinite iterable types. Not to mention that there are a few more already built in. – deceze Apr 09 '21 at 21:00
  • Ok now i see what you mean but the basic ones are mentioned above : Lists, tuples, Dictionaries, Strings and Sets. Iterables are in the matter of fact infinit. – Lahmidi Mustapha Apr 09 '21 at 21:08