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.
CodePudding user response:
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']
CodePudding user response:
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
CodePudding user response:
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