user4999187
user4999187

Reputation: 33

Print Successive Numbers That Appear Twice?

I want to print out each item in Python and number them successively, but each number should appear twice.

1 Item
1 Item
2 Item
2 Item
3 Item
3 Item

Upvotes: 2

Views: 109

Answers (3)

Dan O'Boyle
Dan O'Boyle

Reputation: 3766

If I understand your question, you want to use enumerate

From the docs:

enumerate(sequence, start=0)

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating... https://docs.python.org/2/library/functions.html#enumerate

Example code:

items = ['item1', 'item2', 'item3']

for idx, item in enumerate(items):
  print idx, item
  print idx, item

Would yield the following output:

0 item1
0 item1
1 item2
1 item2
2 item3
2 item3
[Finished in 0.1s]

(If you're saying you only want them to appear once, omit one of the print statements.)

Upvotes: 1

Vikas Ojha
Vikas Ojha

Reputation: 6950

for i, item in enumerate(items):
    print i, item
    print i, item

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

items = ['Item'] * 6
for i, item in enumerate(items, start=1):
    number = (i + 1) / 2
    print('{} {}'.format(number, item))

Upvotes: 1

Related Questions