2

Is it possible to dynamically create loops in Python and store some values?

For example a 2 loop of loops:

for word1 in word_list:
    for word2 in word_list:
        final_word=word1+word2

A three loop of loops:

for word1 in word_list:
    for word2 in word_list:
        for word3 in word_list:
              final_word=word1+word2+word3
  • 2
    It might be better to post the problem you're trying to solve. This might be indicative of thinking about it in a different way. – sdasdadas Jun 22 '14 at 20:04
  • 2
    Any particular reason not to use `itertools.product(word_list, repeat=some_number)`? – tobias_k Jun 22 '14 at 20:09
  • Thanks! that is what i was looking for. I did some researches but as i was searching with "dynamically" i didn't found the right post. –  Jun 22 '14 at 20:11
  • I think tobias_k is pointing you to what you are wanting ... – Joran Beasley Jun 22 '14 at 20:12
  • Can some one remove the duplicated tag? or should i ask again? because i imagine that only people with a lot of reputation will be able to answer –  Jun 22 '14 at 21:30
  • 1
    You do not need to ask again, that's for sure. You can, however, keep improving your post. – Lev Levitsky Jun 22 '14 at 21:47

2 Answers2

0

Are you just trying to get all n-combinations of words in the list, i.e. if the list is ['a','b','c'], do you just want ['aaa','aab','aac','aba','abb','abc','aca',etc...]? If so, just map join over the product, where your repeat value is how many words you want to join:

map(''.join, itertools.product(wordlist, repeat=n))
Gary Fixler
  • 5,632
  • 2
  • 23
  • 39
  • Yes, this is exactly what i want to do. I'm kinda confused, does the map function is giving me final_word? or is making a list with all the combinations? i did final_word=map(''.join, itertools.product(word_list, repeat=n)) But is not working,(maybe it's an error of my program, but i want to know if i'm doing it right. I get no error, but some times i can't see errors on my curses program) –  Jun 22 '14 at 22:24
  • I see that your function creates a list. I think that it is an interesting answer but the problem is that if there are too many combinations it will get slow and consume a lot of ram no? that's what i liked about the loop of loops, the fact of avoiding to create a big list. Also, im wondering if the map function allows weird chars like "©ú#@" , i made a test and since i cant see what is happening, i create a function to write the final_word in a file, but im not getting the 'weird chars' –  Jun 22 '14 at 22:37
  • > weird chars works, it was my mistake. (it wasn't possible to edit the previous post) –  Jun 22 '14 at 22:47
  • Yes, `map` will generate an entire list. If you want a lazy version that doesn't create everything up front, you could use the lazy version of `map` - [itertools.imap()](https://docs.python.org/2/library/itertools.html#itertools.imap). – Gary Fixler Jun 22 '14 at 22:54
  • Map just takes a function of one argument and a sequence, and gives back a list of the results of calling the function on each item of the sequence. If a function `times2` takes a number and returns the number doubled, then `map(times2, [1,2,3])` would result in `[2,4,6]`. That's all map is. – Gary Fixler Jun 22 '14 at 22:57
0
import time

startedsomething = 0
finishingoff = 1
roundtwo = 2
roundone = 1
def repeat():
            def one():
                if roundone < roundtwo:
                    print("this is round ONE 1111111 coming through")
            one()
            time.sleep(3)
            def two():
                global roundone, roundtwo
                if roundone == roundtwo:
                    print("this is round TWO 2222222 coming through if finishingoff is     set to 10 that would be 9 rounds and this code should show up 4 times")
                    roundtwo += 1
                    roundone -= 1
                roundone += 1
            time.sleep(3)
            two()
            print("This is some interesting code I hope you like this loop")
            print("Whats really happening is that First round one gets picked up than     this code, than round two, than this code than round one than this code round one can     referr to something in round two especially if you have a general variable on top and a     global variable the same in round two and round two can refer to round one")
            time.sleep(3)            
            def startingsomething():
                global startedsomething
                if finishingoff > startedsomething:
                    print("Now you happining look at you you started something, lets     make sure, you put everything here you want python to remember until your finishing off")
                    time.sleep(3)
                    startedsomething += 1                    
            startingsomething()            
            def finalwords():
                global finishingoff
                if finishingoff == startedsomething:
                    print("you've come to the end of your loop")
                    time.sleep(3)
                    finishingoff += 1                   
            finalwords()            
while finishingoff < 10:
    repeat()
            
        
  • Please, provide some context to your answer. It will help others to understand the answer provided by you easily. – Pawara Siriwardhane Apr 11 '21 at 06:24
  • First I was looking at the topic "dynamically create some loops and store some values" hence the code is an example of such. The code I made, contains 5 loops. First one called "repeat" whose function is, (and that is what it is, a function,) to loop through your main code, not the code above it though. In the code above it are global variables, (no need to call them global in your code, since they are not part of any function.) You can re-value these variables, within any function within your loop, by tagging them "global" first. The rest are "if" statements. Hint: add more "if's"cheers – Randolf Enns Friesen Apr 11 '21 at 08:59
  • For the example given by the question: Your using the "for" loop. As I understand Python, the "for" loop is to extract value, not add or change value. If all you want to do is extract and store value, than yes you use the "for" loop. Of course you can use "for" in conjunction with the dynamic loop I provided. I find using "for" for dynamic loops very confusing. – Randolf Enns Friesen Apr 11 '21 at 09:36
  • Correction, on my first coment: 1 loop 5 functions NOT 5 loops, even though you could make a "while" loop in each function. I don't recomend, more Than one "while" loop. Its too confusing. "for" I would have various, but, like I said to extract value, from a python array (which is just a list of lists in python.) – Randolf Enns Friesen Apr 11 '21 at 10:07
  • As for context, the tricky repeat on function one and two I provided, can be used in any context, including cnc machinery programing. Also, if you want to add a function three to those just copy the set up on function one and two and paste it to function two and three just with different variable names. And what you would have is: fn one takes turns with fn two and three, while fn two and three take turns within that "turn." – Randolf Enns Friesen Apr 11 '21 at 10:29
  • What I like about "if" statements is that no matter the size of the code preceeding if conditions are met there is no latency or harm if conditions aren't met. The program just skips instantly to the next block of code, even if you have 2000+ lines of code to be executed if conditions are met. Its like those 2000+ lines of code don't even exist in the mean time. – Randolf Enns Friesen Apr 11 '21 at 11:16