Search code examples
pythonlisttuples

Making a list of tuples with sequential elements in python


Assuming K an integer number, Y a pd.Dataframe() and Z a list(). How can I make a list of tuples with the following sequential structure for the first element of each tuple:

[(K,Y,Z), (K+1,Y,Z), (K+2,Y,Z), (K+3,Y,Z), (K+4,Y,Z),......,(K+N,Y,Z)] , for any positive value of N.


Solution

  • Python uses 0-based indexing by default. Therefore, if you actually want your counter to go from 1 to N, in python you'll have to specify it. otherwise it'll go from 0 to N-1, which is the exact same number of iterations, but it will not return the same numbers.

    You can use a for loop:

    final_list :
    for ii in range (1,N+1):
        final_list.append((K+ii, Y, Z))
    

    Or if you're looking for something a little fancier, use list comprehension :

    final_list = [(K+ii, Y, Z) for ii in range (1,N+1)]
    

    Although I'd advise against it if you can't read it as easily. Readability counts, and it's not worth the trouble if you can't understand it afterwards.