Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of ints into a list of tuples python

Tags:

python

list

[1, 109, 2, 109, 2, 130, 2, 131, 2, 132, 3, 28, 3, 127] I have this array and I want to turn it into a list of tuples, each tuple has 2 values in. so this list becomes [(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]

like image 354
miik Avatar asked Apr 06 '13 14:04

miik


People also ask

How do I make a list into a list of tuples in Python?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.

How do I make a list into a list of tuples?

A simple way to convert a list of lists to a list of tuples is to start with an empty list. Then iterate over each list in the nested list in a simple for loop, convert it to a tuple using the tuple() function, and append it to the list of tuples.

Can we convert list to tuple in Python?

Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.


2 Answers

You can use zip combined with slicing to create a new list of tuples.

my_new_list = zip(my_list[0::2], my_list[1::2])

This would generate a new list with the following output

[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]

The process behind this is quite simple. We first split the existing list into two new lists using slicing.

print my_list[0::2] # [1, 2, 2, 2, 2, 3, 3]
print my_list[1::2] # [109, 109, 130, 131, 132, 28, 127]

Then use zip to combine these two lists into one list of tuples.

print zip(my_list[0::2], my_list[1::2])
like image 196
eandersson Avatar answered Sep 28 '22 01:09

eandersson


>>> it = iter(L)
>>> zip(*[it]*2)
[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]

Explanation

it = iter(L) creates iterator on the initial list

[it]*2 crates the list consisting of the same iterator twice.

* used at the first place in the parameter is used to unpack the parameters, so that zip(*[it]*2) turns into zip(it,it). Though you can use zip(it,it), zip(*[it]*2) is a more general construction, which can be extended to any number of values in the resultant tuple.

The core of this approach is that zip on each iteration tries to get one value from each argument. But it turns out that all the arguments are effectively the same iterator, so it yields every time a new value.

like image 35
ovgolovin Avatar answered Sep 28 '22 00:09

ovgolovin