How can I convert a list into a list of tuples? The tuples are composed of elements at even and odd indices of the list.For example, I have a list [0, 1, 2, 3, 4, 5]
and needs to be converted to [(0, 1), (2, 3), (4, 5)]
.
One method I can think of is as follows.
l = range(5)
out = []
it = iter(l)
for x in it:
out.append((x, next(it)))
print(out)
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.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.
Initial approach that can be applied is that we can iterate on each tuple and check it's count in list using count() , if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set() .
Fun with iter
:
it = iter(l)
[*zip(it, it)] # list(zip(it, it))
# [(0, 1), (2, 3), (4, 5)]
You can also slice in strides of 2 and zip
:
[*zip(l[::2], l[1::2]))]
# [(0, 1), (2, 3), (4, 5)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With