0
packed_source_stream_offsets = bytearray()
for x in source_stream_offset:
    packed_source_stream_offsets += varint.encode(x)

Is there a way I can do this on fewer lines or make it more compact? I'm trying to make my code more compact, and I'm wondering if there's a shorter way of doing this.

martineau
  • 119,623
  • 25
  • 170
  • 301
JZQAr9kW
  • 7
  • 2

1 Answers1

0

It's always a bit difficult to answer when there is no reproducible code (e.g. not knowing what source_stream_offset is, or where varint comes from, but I think this should apply in general:

  1. Instead of appending you can use an empty string or byte to join individual parts
  2. You can map over the function rather than using an explicit value

That should yield something like:

bytearray(b''.join(map(varint.encode, source_stream_offset)))

Note: If you're not comfortable with the map syntax, you can also use a list comprehension like:

 bytearray(b''.join([varint.encode(x) for x in source_stream_offset]))
Elias Mi
  • 611
  • 6
  • 14
  • You can also use a generator expression instead of a list comprehension to avoid creating an intermediate list (just remove the square brackets). – yut23 May 17 '22 at 23:14
  • Actually, list comprehensions are better for `''.join()`: https://stackoverflow.com/a/9061024 – yut23 May 19 '22 at 20:51