0

How do you set the length of a list (defined, for example, as "array") in Python?

For example, Java allows you to define an array (which I would say is equivalent to a Python list) as follows: "int[] array = new int[desired-length];". In Python, however, I have not found a way to do this right off the bat. I have to either define each item right away, or for-loop my way through adding items to the end. Can I define the length right away, and THEN for-loop my way through (in my case, I'm trying to assign each item a random integer value), giving each item the random value?

22nd Feb 2019, 8:39 PM
ShadowDashNinja [GD]
ShadowDashNinja [GD] - avatar
5 Answers
+ 12
In Python there is no actual need or reason to define lists (or any mutable variables) with pre-set sizes. Only immutable ones kind of have to, as you declare them as constant for the runtime. Still, if you need to instantiate a list of a given dimension you can use a list expression to do that, like: l = [None for i in range(20)] or simply: l = [None] * 20
22nd Feb 2019, 8:59 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 12
On the other hand, if you need an array type - you can use Python numpy module, which supports array-like tensors (they are still called arrays though :) import numpy as np a = np.empty(20) # will create an array of size (20,) with an interesting value representation of "emptiness" ;)
22nd Feb 2019, 9:05 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 1
Kuba SiekierzyƄski... in the fitst 2 examples i get a list with 20 None items inside? in your, 3rd example i get a list of "interesting value representations " as you called them. Just wanna make sure if this is right or am i doing something wrong?
22nd Feb 2019, 10:07 PM
Theuns Booysen
Theuns Booysen - avatar
+ 1
Theuns Booysen, he was using "None" as filler code. What he means is that you can fill it with whatever you want. In my case, I was filling the array with random integers.
22nd Feb 2019, 10:16 PM
ShadowDashNinja [GD]
ShadowDashNinja [GD] - avatar
+ 1
Thanks, was playing with the code and i figured it out!!! Thanks for bringing up the question and helping me to learn!!!
22nd Feb 2019, 10:18 PM
Theuns Booysen
Theuns Booysen - avatar