kuslahne
kuslahne

Reputation: 730

join new tuple to first list of tuples in Python

I am newbie to python and don't know how to do this.

I have a list of tuples which represent data and another list which represents header. I need a set of combinations into new tuples to look from this.

data = [( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')]
header = ["ID", "MyData"]

into this

newdata = [("ID", "MyData"),( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')]

please help.

Upvotes: 1

Views: 437

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61526

Creating a completely new value, without any temporaries:

[tuple(header)] + data

Addition of two lists concatenates them. We turn the header, which is a list, into a tuple (since we want a tuple of its data in the final result), and then make a list that contains it, so that we can glue the two lists together.

Upvotes: 1

arunkumar
arunkumar

Reputation: 34053

This should do it

data.insert(0,tuple(header))
newdata = data

Upvotes: 0

Rafe Kettler
Rafe Kettler

Reputation: 76955

Here:

data.insert(0, tuple(header))

Note that this will modify data in-place. You can achieve the same results without modifying data like so:

newdata = [tuple(header)]
newdata.extend(data)

Upvotes: 5

Related Questions