Here's my code:
txt = '''food: bacon, eggs, toast
drinks: orange juice, coffee'''
groups = txt.split('\n\n')
for group in groups:
nameslist = group.split(': ').pop(0)
print(groups)
print(nameslist)
The output for print(groups) is as expected: ['food: bacon, eggs, toast', 'drinks: orange juice, coffee']
I'm trying to get a list ['food', 'drinks'] as the output for print(nameslist), but Python gives me 'drinks' as the output, as if it only grabs from the second element rather than iterating.
The problem with your approach is that nameslist is never initialized, and is reset at each iteration, you probably wanted to do:
txt = '''food: bacon, eggs, toast
drinks: orange juice, coffee'''
nameslist = [] # initialize namelist
groups = txt.split('\n\n')
for group in groups:
nameslist.append(group.split(': ').pop(0)) # append instead of overwriting
print(groups)
print(nameslist) # ['food', 'drinks']
Additionally, you can throw away the loop and use a list comprehension to achieve that:
namelist = [x.split(':')[0] for x in groups] # ['food', 'drinks']
The way you currently have it set up, you are not adding anything to a list. You are simply setting the variable nameslist as the last pop. Try this:
nameslist = [] # Define an empty list
groups = txt.split('\n\n')
for group in groups:
nameslist.append(group.split(': ').pop(0)) #Add popped element to the list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With