-2

''' return a new string containing the 2 strings interwoven or zipped together. ex: Input: 'hi' 'ha' Ouput: hhia

Input: 'lzr','iad' output: lizard

def interleave(str1, str2):
    ls1 = zip(str1, str2)
    print(list(ls1))
    # prints [('h', 'h'), ('i', 'a')] as expected
    ls2 = [''.join(x) for x in ls1]
    print(ls2)
    # prints below. not as expected
    # output: []
    print(list(ls2))
    # prints empty list. not as expected.
    # output: []
    # Below prints hhia correctly
    ms1 = ''.join(''.join(x) for x in zip(str1,str2))
    print(ms1)
    # Output: hhia

interleave('hi','ha')

its working when i give in a single line (ms1). when i split and give its not working (ls1, ls2). Can anyone advise the root cause? '''

  • 1
    Your last statement is an assignment, not a value... What happens if you just put `s2` oh a line by itself at the end? – Edward Peters Nov 22 '22 at 02:08
  • Please research about the problem a little bit, before making a question for it here.As @EdwardPeters stated you are doing an assingment in the repl, put `s2` on a newline to see it's value – Irtiza Babar Nov 22 '22 at 05:34
  • To be fair this is a google-resistant problem - there's no immediately obvious keyword to search on, and the assignment thing isn't necessarily obvious (or the case in all languages). They also clearly played around trying to fix it, as they have a working version. I don't think it's a bad question. – Edward Peters Nov 22 '22 at 14:05
  • It's working fine. I don't know how you got that output. In the future, please make a [mre] before asking a question, to isolate the problem. And welcome to Stack Overflow! Please take the [tour] and read [How to ask a good question](/help/how-to-ask), which has tips like how to write a good title. – wjandrea Nov 22 '22 at 16:49
  • 1
    code updated fully now. Hope this makes everyone clear on the issue, – Chidambaram P Nov 22 '22 at 17:02
  • @ChidambaramP That's totally different code. In the future, please ask a new question instead of changing what you're asking. This is now a duplicate of this existing question: [Why can't I iterate twice over the same data?](/q/25336726/4518341) – wjandrea Nov 22 '22 at 18:53
  • 1
    @wjandrea.. this question is related to zip function. since its an iterator related.. doesnt a duplicate to the existing question. understand before u comment. – Chidambaram P Nov 22 '22 at 22:02

1 Answers1

2

Because zip() is a python iterator. Once you retrieve the values of ls1 in third line(print(list(ls1))), the ls1 become empty.

Try this case, it would be more clear:

def interleave(str1, str2):
    ls1 = zip(str1, str2)
    print(list(ls1))  # prints [('h', 'h'), ('i', 'a')] as expected
    print(list(ls1))  # empty
    ls1 = zip(str1, str2)
    print(list(ls1))  # prints [('h', 'h'), ('i', 'a')] as expected



interleave('hi','ha')
theabc50111
  • 421
  • 7
  • 16