Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing every 2 elements in a tuple

I have looked at several questions Iterating over every two elements in a list and Python "Every Other Element" Idiom, they have yielded an answer that I might be forced to use but which I feel there is a better approach to; what I want to do with the code below is to be able to print every two or every 4 elements

 Gun_rack =(
         'Gun 1:', 'Colt New Frontier 44 Special', 'Cal:.44     ', 'Weight: 2.8  lbs', 'Ammo Capacity  :6',
         'Gun 2:', 'Smith & Wesson SW1911DK'  ,    'Cal:.45 ACP ', 'Weight: 2.6  lbs', 'Ammo Capacity  :9',
         'Gun 3:', 'Heckler & Koch P2000SK V2',    'Cal.357     ', 'Weight: 1.50 lbs', 'Ammo Capacity :13',             
         'Gun 4:', 'Magnum Research Desert Eagle', 'Cal.50      ', 'Weight: 4.46 lbs', 'Ammo Capacity  :7',
         'Gun 5:', 'Heckler & Koch MP5K ',         'Cal 9mm     ', 'Weight: 4.78 lbs', 'Ammo Capacity :30',
         )

I know that if I used a dictionary I could print every key and value argument like the example given in the python tutorial, but the items are in random order hence the tuple

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave

I was hoping to use similar code with either a list or a tuple:

for a ,b in Gun_rack:
   print a,b

or

for a,b,c,d, in Gun_rack:
  print a,b,c,d,

I think I should have mentioned what the output should have been, instead of stepping trough the tuple and printing every 2nd element or every 4th element, it should go through the tuple and print every 2 elements then the next 2 elements until the end of the tuple.

like image 468
H.J_Rios Avatar asked Dec 26 '22 17:12

H.J_Rios


1 Answers

To print every other element:

for elem in Gun_rack[::2]:
   print elem

and every other element, starting with the second one:

for elem in Gun_rack[1::2]:
   print elem

Of course, to do every fourth element, just change the 2 to a 4. The reason this works is because slice objects (which are created implicitly when you do a[:]) take 3 arguments -- start,stop,stride. Here, we're specifying the stride.

like image 98
mgilson Avatar answered Dec 29 '22 08:12

mgilson