How would I set a list that only holds up to ten elements?
I'm obtaining input names for a list using the following statement:
ar = map(int, raw_input().split())
and would like to limit the number of inputs a user can give
After getting the ar
list, you may discard the remaining items via list slicing as:
ar = ar[:10] # Will hold only first 10 nums
In case you also want to raise error if list has more items, you may check it's length as:
if len(ar) > 10:
raise Exception('Items exceeds the maximum allowed length of 10')
Note: In case you are making the length check, you need to make it before slicing the list.
I created a custom class overwriting the list class to do this for me
class LimitedLengthList(list):
def __init__(self, seq=(), length=math.inf):
self.length = length
if len(seq) > length:
raise ValueError("Argument seq has too many items")
super(LimitedLengthList, self).__init__(seq)
def append(self, item):
if len(self) < self.length:
super(LimitedLengthList, self).append(item)
else:
raise Exception("List is full")
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