Convert a list to a list of 2 tuples
I have a list:
list = [1, 2, 3]
I want to get this list and add a tuple so that this list becomes like this
T_list = [(1,x), (2, x), (3,x)]
How should I do it?
+3
Fredo ovelha
source
to share
3 answers
Use a simple list comprehension for this:
>>> your_list = [1, 2, 3]
>>> x = 100
>>> your_list_with_tuples = [(k, x) for k in your_list]
>>> your_list_with_tuples
Output
[(1, 100), (2, 100), (3, 100)]
Also, don't name variables list
, dict
etc., because they hide built-in types / functions.
+10
coldspeed
source
to share
Understanding the list will do the trick:
t_list = [(y,x) for y in original_list]
Besides, the commentator is right. Don't include your lists list
. This is a built-in function. Using this for something else can cause problems on the line.
+3
Iain Dwyer
source
to share
Here's my attempt, although I'm not an expert.
lis = [1,2,3] tup = (4, 5, 6) new_tup = tuple(lis) new_lis = [] for i in range(0,3): data = (new_tup[i],tup[i]) new_lis.append(data) print(new_lis)
+1
goddar
source
to share