Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list consisting of elements popped from another list (Python)

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.

like image 599
BorisAdasson Avatar asked Mar 08 '26 04:03

BorisAdasson


2 Answers

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']
like image 183
RMPR Avatar answered Mar 10 '26 17:03

RMPR


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
like image 38
Matt Gallant Avatar answered Mar 10 '26 19:03

Matt Gallant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!