Python make list of tuples from two lists and a constant

Viewed 1696

I would like to make a list of tuples using two lists and a constant, as follows, I'd like to generate ob in the fast way possible. I need to make about a hundred thousand of these, so time matters...

On average the size A and B have a length of about 1000

constant = 3
A = [1,2,3]
B = [0.1,0.2,0.3]
ob = [(3,1,0.1),(3,2,0.2),(3,3,0.3)]

I know zip(A,B) can create a list of tuples but I need the constant at the beginning. Here is the code I am using at them moment, I was wondering if there is a faster way to do this

ob = []
for i in xrange(len(A)):
    a = A[i]
    b = B[i]
    ob.append((constant,a,b))

print ob
3 Answers

You could use itertools.repeat:

from itertools import repeat

ob = list(zip(repeat(constant), A, B))

I suggestion the following solution still based on zip() built-in function, without any needed import directive:

constant = 3
A = [1,2,3]
B = [0.1,0.2,0.3]

ob = list(zip([constant]*len(A), A ,B))

print(ob)  # [(3,1,0.1),(3,2,0.2),(3,3,0.3)]

use itertools.cycle

import itertools 
ob = list( zip( itertools.cycle([3]) , A , B ) )
Related