Tomasz Przemski
Tomasz Przemski

Reputation: 1127

Sequential list with pairs of the same prefix

I have the simplest possible code for creating string with integer:

x = []
for i in range(6): 
    x.append('a' + str(i))

,witch creating that output:

['a0', 'a1', 'a2', 'a3', 'a4', 'a5']

But how could the condition to create a list in this form look like:

 ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']

I tried this way:

x = []
for i in range(6): 
   if i%2==0: 
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

Upvotes: 0

Views: 43

Answers (3)

Blownhither Ma
Blownhither Ma

Reputation: 1471

Duplicating code as described in other answers works well.

Other interesting options include:

x = []
for i in range(6 * 2):
    x.append('a' + str(i // 2))

# list comprehension, expect better performance with this
x = ['a' + str(i//2) for i in range(6 * 2)]

# if you have numpy
import numpy as np
temp = ['a' + str(i) for i in range(6)]
x = np.array(temp).repeat(2)

Upvotes: 2

user2390182
user2390182

Reputation: 73450

This comprehension makes use of integer division:

x = ['a' + str(i//2) for i in range(6)]

It can create lists of odd length, too ;-)

Upvotes: 3

Van Peer
Van Peer

Reputation: 2167

x = []
for i in range(3): 
    x.append('a' + str(i))
    x.append('a' + str(i))

Output

['a0', 'a0', 'a1', 'a1', 'a2', 'a2']

Upvotes: 2

Related Questions