Limit the length of a Python list

2019-06-23 16:32发布

问题:

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

回答1:

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.



回答2:

You can also do something like this.

n = int(input())
a = [None] * n

It will create a list with limit n.