Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list into list of tuples of every two elements [duplicate]

Tags:

python

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)
like image 677
Edmund Avatar asked Dec 31 '18 17:12

Edmund


People also ask

How do you convert a list into a list of tuples?

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.

Can list and tuple have duplicate values?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Can we have duplicate elements in tuple?

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.

How do you find duplicates in tuples?

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() .


1 Answers

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)]
like image 200
cs95 Avatar answered Oct 22 '22 03:10

cs95