Question about printing multiple items in a list in a specific order in Python

Viewed 64

So I've been racking my brain on this for a while and decided to reach out to you fine folks. The issue I'm trying to figure out is how to print items in a list in a specific order. I have a list:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']

And I want to have my results look like this:

'The dog goes woof'
'The cat goes meow'
'The horse goes neigh'
'The cow goes moo'

So far I have tried the following code:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']

for i in m[:4]:
    print('The ' + i + ' goes ' + str(x for x in m[4:]))

My results are:

'The dog goes <generator object <genexpr> at 0x01177C70>'
'The cat goes <generator object <genexpr> at 0x01177C70>'
'The horse goes <generator object <genexpr> at 0x01177C70>'
'The cow goes <generator object <genexpr> at 0x01177C70>'

Now I found out that the 'x' statement just returns a 'None' value which is why I don't get the results I want. Can anyone give me some insight? Any help will be greatly appreciated. Thanks in advance.

4 Answers

You can zip through list:

m = ['dog','cat','horse','cow','woof','meow','neigh','moo']

for x, y in zip(m, m[4:]):
    print(f'The {x} goes {y}')

# The dog goes woof
# The cat goes meow
# The horse goes neigh
# The cow goes moo

For any length list, you can do:

for x, y in zip(m, m[len(m)//2:]):
    print(f'The {x} goes {y}')

The expression (x for x in m[4:]) is called a generator expression and is an object that can generate things, probably not really what you want.

This will solve your problem:

m = ['dog','cat','horse','cow','woof','meow','neigh','moo']

for i in range(4):
    print('The ' + m[i] + ' goes ' + m[i + 4])

The idea of a list or array is generally to hold homogenous data -- if you have animal names and animal noises, those are distinct and the data structure should distinguish them.

e.g. split your list into two lists, and zip those into a list of pairs

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']
for pair in zip(m[:4], m[4:]):
  print(f"the {pair[0]} goes {pair[1]}")

Though Austin's "for x,y" below is more idiomatic

Harcoding is fine, but go with generic design by splitting it in two parts:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']
for pair in zip(m[:len(m)/2], m[len(m)/2:]):
  print(f"the {pair[0]} goes {pair[1]}")
Related