1

How can I add a value of a list to its own sublist? Input list:

list = ['apple', 'tesla', 'amazon']

My approach so far:

While True:
 
    list = []

    for comp in list:

            #do some modification

            list.append(comp)

Desired printed output is:

'apple', 'apple','apple', etc.
'tesla', 'tesla','tesla', etc.
'amazon','amazon','amazon', etc.
Jones L
  • 9
  • 3
  • What do you mean by an "infinite loop" ? What are you trying to accomplish? – Mortz May 18 '22 at 09:57
  • Does this answer your question? [Modifying list while iterating](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating) – nfn May 18 '22 at 09:58
  • 1
    @Mortz I want to have the value e.g. 'apple' to be ended, till a condition is met and a 'break' statement is executed. So apple shall be added over and over again. I need to have the the sub-lists in physically separated lists. not just a print statement at the end of each iteration. – Jones L May 18 '22 at 09:59

3 Answers3

0

If you change your orignal list to a list of lists it can be done as:

list = [['apple'], ['tesla'], ['amazon']]

while True:
    for i in range(len(list)):
        list[i].append(list[i][0])

The output on each iteration would be something like:

# for iteration 1
['apple', 'apple']
['tesla', 'tesla']
['amazon', 'amazon']

# for iteration 2
['apple', 'apple', 'apple']
['tesla', 'tesla', 'tesla']
['amazon', 'amazon', 'amazon']
0
list = ['apple', 'tesla', 'amazon']
for idx, item in enumerate(list):
    text = (list[idx]+",")*len(list)
    print(text[:-1])
apple,apple,apple
tesla,tesla,tesla
amazon,amazon,amazon
uozcan12
  • 404
  • 1
  • 5
  • 13
0

I can think of a couple of ways - I am using the length of each item in the list to define a condition here as you did not specify the condition you are using to move on to the next item -

Option 1 - using a for with a while loop

l = ['apple', 'tesla', 'amazon'] 
x = 0
for comp in l:
    while x < len(comp):
        print(comp)
        x += 1
    x = 0

Option 2 - using while with a iter

l = ['apple', 'tesla', 'amazon'] 
x = 0
it = iter(l)
while True:
    try:   
        item = next(it)
        while x < len(item):
            print(item)
            x += 1
        x = 0
    except StopIteration:
        break

In both cases - the output is

apple
apple
apple
apple
apple
tesla
tesla
tesla
tesla
tesla
amazon
amazon
amazon
amazon
amazon
amazon
Mortz
  • 4,654
  • 1
  • 19
  • 35