Reputation: 121
I am currently learning Python (I have a strong background in Matlab). I would like to write a loop in Python, where the size of the array increases with every iteration (i.e., I can assign a newly calculated value to a different index of a variable). For the sake of this question, I am using a very simple loop to generate the vector t = [1 2 3 4 5]
. In Matlab, programming my desired loop would look something like this:
t = [];
for i = 1:5
t(i,1) = i;
end
I have managed to achieve the same thing in Python with the following code:
result_t = []
for i in range(1,5):
t = i
result_t.append(t)
Is there a more efficient way to assign values to an array as we iterate in Python? Why is it not possible to do t[i,1] = i
(error: list indices must be integers or slices, not tuple) or t.append(t) = t
(error: 'int
' object has no attribute 'append')?
Finally, I have used the example above for simplicity. I am aware that if I wanted to generate the vector [1 2 3 4 5]
in Python, that I could use the function "np.arange(1,5,1)
"
Thanks in advance for your assistance!
-> My real intention isn't to produce the vector [1 2 3 4 5], but rather to assign calculated values to the index of the vector variable. For example:
result_b = []
b = 2
for i in range(1,5):
t = i + b*t
result_b.append(t)
Why can I not directly write t.append(t)
or use indexing (i.e., t[i] = i + b*t
)?
Upvotes: 12
Views: 131609
Reputation: 41
data = ['Order-'+str(i) for i in range(1,6)]
print(data)
>>> ['Order-1', 'Order-2', 'Order-3', 'Order-4', 'Order-5']
Upvotes: 1
Reputation: 980
The range
function returns an iterator in modern Python. The list
function converts an iterator to a list. So the following will fill your list with the values 1 to 5:
result_t = list(range(1,6)) # yields [1, 2, 3, 4, 5]
Note that in order to include 5
in the list, the range argument has to be 6
.
Your last example doesn't parse unless you assign t
a value before the loop. Assuming you do that, what you're doing in that case is modifying t
each time through the loop, not just producing a linear range. You can get this effect using the map
function:
t = 0
b = 2
def f(i):
global t
t = i + b*t
return t
result_b = list(map(f, range(1, 5))) # Yields [1, 4, 11, 26]
The map
function applies the f
function to each element of the range and returns an iterator, which is converted into a list using the list
function. Of course, this version is more verbose than the loop, for this small example, but the technique itself is useful.
Upvotes: 1
Reputation: 584
a better example from UI Testing using selenium.
print('Assert Pagination buttons displayed?')
all_spans = self.web_driver.find_elements_by_tag_name('span')
# Identify the button texts
pagination_buttons = ["Previous Page", "Next Page", "First Page"]
# Filter from all spans, only the required ones.
filtered_spans = [s for s in all_spans if s.text in pagination_buttons]
# From the filtered spans, assert all for is_displayed()
for a_span in filtered_spans:
assert a_span.is_displayed()
print('Asserted Pagination buttons displayed.')
Upvotes: 0
Reputation: 9267
Appending elements while looping using append()
is correct and it's a built-in method within Python lists
.
However you can have the same result:
Using list comprehension:
result_t = [k for k in range(1,6)]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using +
operator:
result_t = []
for k in range(1,6):
result_t += [k]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using special method __iadd__
:
result_t = []
for k in range(1,6):
result_t.__iadd__([k])
print(result_t)
>>> [1, 2, 3, 4, 5]
Upvotes: 22