0
How to set a limit for a list?
A = [] This list should only be able to contain 5 numbers, and one shouldnt be able to append more than that.
11 Answers
+ 3
You can do this using loops
l = []
for i in range(5):
item = input()
l.append(item)
print(l)
+ 2
when ever you will append a new element just check if the size is 5 or not... if yes then dont append....
simple
+ 1
A `list` is mutable type AFAIK, there is a `frozenset` but it's more like a `set` than it is a `list`. Why not use a `tuple` which is immutable?
+ 1
Ipang u mean with conditions when iâm appending new values inside a loop right?
+ 1
Lol more like:
â˘â˘â˘
empList = []
for i in range(0,20):
empList.append(i)
if len(empList) >= 6:
break
print(empList)
â˘â˘â˘â˘
#my list will stop adding stuff once the len is 5, so basically the limit is 5.
0
Ipang u cant add to a tuple can you?
0
No we can't, but isn't that the point? that it doesn't support item addition?
0
Ipang i just want a list that i can append 5 numbers to only not more. Not really a tuple, since i have to be able to append to it
0
Without your intervention (mitigation code) at the event of item addition, I don't know how it can be done. A `list` is a mutable type nonetheless.
0
Once you have 5 item in the list, convert it to a tuple.
Show your code so we can see how you intend to fill the list.
0
class List(list):
def append(self, item):
if len(self) < 5: # limited to 5 values/items
self.insert(len(self), item)
a = List()
for x in range(1, 20): # loops from 1 to 19
a.append(x) # see append method of List (limited to 5 values/item)
print(a)
a.append(10) # will not be appended.
print(a)