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.

24th Feb 2022, 3:52 AM
Lenoname
11 Antworten
+ 3
You can do this using loops l = [] for i in range(5): item = input() l.append(item) print(l)
24th Feb 2022, 5:29 AM
Simba
Simba - avatar
+ 2
when ever you will append a new element just check if the size is 5 or not... if yes then dont append.... simple
24th Feb 2022, 4:26 AM
Md. Mursalatul Islam Pallob
Md. Mursalatul Islam Pallob - avatar
+ 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?
24th Feb 2022, 4:08 AM
Ipang
+ 1
Ipang u mean with conditions when i’m appending new values inside a loop right?
24th Feb 2022, 5:01 AM
Lenoname
+ 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.
25th Feb 2022, 8:53 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
0
Ipang u cant add to a tuple can you?
24th Feb 2022, 4:32 AM
Lenoname
0
No we can't, but isn't that the point? that it doesn't support item addition?
24th Feb 2022, 4:34 AM
Ipang
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
24th Feb 2022, 4:49 AM
Lenoname
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.
24th Feb 2022, 4:51 AM
Ipang
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.
25th Feb 2022, 6:43 PM
rodwynnejones
rodwynnejones - avatar
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)
26th Feb 2022, 11:07 AM
rodwynnejones
rodwynnejones - avatar