2

I have a list E = [1,2,3,4,5,6,7,8] and I will like to convert it into E = [{1,2}, {3,4}, {5,6}, {7,8}] in the least computationally expensive manner. In particular, I will like to extend this to large instances of E.

Is there an efficient way to do this in Python (3.5 & later)?

Remark: E will always be given as an even-sized list, as I am working on graphs related topics

Stoner
  • 846
  • 1
  • 10
  • 30

3 Answers3

3

I believe the best method would be using iter+zip in a list comprehension

s = iter(E)
[{a,b} for a,b in zip(s,s)]

Explanation: zip(s,s) performs a pretty efficient pairwise grouping of E if s is its iter.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
2

You can iterate over a rolling slice of 2 of E:

[set(E[i:i+2]) for i in range(0, len(E), 2)]

Note that this works for odd-sized lists as well.

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 2
    Thanks for the feedback! I'll accept @RafaelC's answer as it runs somewhat faster than your implementation. P.S. Ran out of up votes for the day, somehow :/ – Stoner Aug 19 '18 at 03:50
1

You can also use zip() plus slicing:

[{x, y} for x, y in zip(E[::2], E[1::2])]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75