-6

first time poster here. I've got this problem on Python that's been doing my head in.

Lets say I have this list:

items = ['6', 'Dogs', '5', 'Cats', '2', 'Birds']

Every element is a string.

What would an easy way to print:

6 Dogs
5 Cats
2 Birds

And so on? I know about dictionaries and tuples and whatnot, but to implement these I would have to change the rest of my code a lot, which I would preferably like to avoid. So how could I print the list like shown above?

Best I've gotten so far is

6 Dogs 5 Cats 2 Birds
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Jimmy_Rustle
  • 319
  • 4
  • 14
  • 4
    This is really not the correct use case for a list. You should rework your code to use a more appropriate data structure for this even if it does seem like a lot of work now. – ydaetskcoR Aug 03 '14 at 11:59
  • It's obvious how to do this with a dictionary, but how would you do it with a whatnot? Or, more relevantly, a tuple, since the code that works with a tuple would almost certainly work unchanged with a list, and you claim to know how to write that… – abarnert Aug 03 '14 at 12:15

1 Answers1

1

You can get two lists, one starts from the beginning and skips every next element and the other starts from the second element and skips every other element. And then you just need to zip (iterate items from both the lists at the same time) the data from both the lists and print them, like this

items = ['6', 'Dogs', '5', 'Cats', '2', 'Birds']
for item1, item2 in zip(items[::2], items[1::2]):
    print item1, item2

Output

6 Dogs
5 Cats
2 Birds

If you print the skipped lists,

print items[::2]
# ['6', '5', '2']
print items[1::2]
# ['Dogs', 'Cats', 'Birds']

Now, zip takes one item at a time from all the lists we supplied and provides us during the iteration with the for loop.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497