Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the length of a Python list

Tags:

python

list

limit

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

like image 200
Waheed Hussain Avatar asked Nov 19 '16 17:11

Waheed Hussain


2 Answers

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.

like image 172
Moinuddin Quadri Avatar answered Oct 04 '22 21:10

Moinuddin Quadri


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")
like image 36
GreenJon902 Avatar answered Oct 04 '22 20:10

GreenJon902