I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:
>>> def split_list(list, seg_length):
... inlist = list[:]
... outlist = []
...
... while inlist:
... outlist.append(inlist[0:seg_length])
... inlist[0:seg_length] = []
...
... return outlist
...
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
Python can also return a segment of a list counting from the end. This is done simply by inserting a negative before the desired numerals within the slice command. Ex: myList[-5] will return your fifth from last entry.
List slicing refers to accessing a specific portion or a subset of the list for some operation while the orginal list remains unaffected. The slicing operator in python can take 3 parameters out of which 2 are optional depending on the requirement.
Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists.
You can use list comprehension:
>>> seg_length = 3
>>> a = range(10)
>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
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