Skip to content
Sign upLog in
← Back to Community

How to print every other item in a list

Profile icon
jn1003491

I have a list of names and I’m trying to get my program to print every other name on the list. I can’t figure out how to do this, so if anyone could help me it would be much appreciated.

Answered by Coder39182 [earned 5 cycles]
View Answer
Voters
Profile icon
jn1003491
Comments
hotnewtop
Profile icon
Coder39182
names = ["Peter", "Bruce", "Steve", "Tony", "Natasha", "Clint", "Wanda", "Hope", "Danny", "Carol"] numbers = ["100", "50", "10", "1", "2", "7", "11", "17", "53", "-8", "-4", "-9", "-72", "-64", "-80"] print(names[::2]) print(numbers[::2]) Output: ['Peter', 'Steve', 'Natasha', 'Wanda', 'Danny'] ['100', '10', '2', '11', '53', '-4', '-72', '-80']

is a compact and easy method to do so

Profile icon
jn1003491

Thank you! This is very helpful :)

@JoeyRueff

Profile icon
RYANTADIPARTHI

Solution

there is a very easy way to do this. Just use a slice method. And this works perfectly to print every other name. try this.

names = ["Peter", "Bruce", "Steve", "Tony", "Natasha", "Clint", "Wanda", "Hope", "Danny", "Carol"] print(names[::2])

bingo! That works. Like that.
That should work

Profile icon
jn1003491

Thanks again!

@RYANTADIPARTHI

Profile icon
jn1003491

What if I want to display only positive numbers?

@RYANTADIPARTHI

Profile icon
Coder39182

@jn1003491

for i in ARRAYNAME: if int(i) % 2 == 0: print(i)
Profile icon
JBloves27

Hello,
To print all you just do the following:

print(names) print(numbers)

However, to do certain ones, like you said every other one, you do the following:

rand_num=0 for i in names: print(names[rand_num]) rand_num+=2

I hope this helps!

Profile icon
Coder39182

@JBYT27
the second example would break since you would add 2 to rand_num 9 times since you're iterating through the for loop for every item in names (there are nine items), meaning it would attempt to print names[18] which does not exist.

Profile icon
JBloves27

oh. then your way prob works XD

@JoeyRueff

Profile icon
mesquite2234
nameOn = 0 for i in names: print(names[nameOn]) nameOn += 2