'Infinite loop over list that adds value to it's own sublist
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.
Solution 1:[1]
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']
Solution 2:[2]
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
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Enric Grau-Luque |
| Solution 2 | uozcan12 |
| Solution 3 | Mortz |
