In the first one you add the arrays of length 10 to the bigger array. So you need to create two arrays.

array1 = []
array2 = []
for j in range(20):
    for i in range(10):
        array1.append(0)
    array2.append(array1)
    array1 = []
print array2

This is equivalent to

array2=[[0 for j in range(10)] for i in range(20)]
Answer from Rolf Lussi on Stack Overflow
๐ŸŒ
Quora
quora.com โ€บ How-do-I-create-an-array-for-loop-in-Python
How to create an array for loop in Python - Quora
Answer (1 of 3): If names is an array, you can loop to process it as such: for name in names: # do something # some other thing If you want to filter one list to create new list, use list comprehension. new names = [val for val in names if val != โ€˜ 'โ€™] This will create a new list...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ trying to create multiple arrays with different names using a for loop
r/learnpython on Reddit: Trying to create multiple arrays with different names using a for loop
April 8, 2023 -

Hi looking for help with a current project Iโ€™m doing. I have a variable Number_Of_items which is an integer number read from a .txt file. Im trying to create a number of arrays equivalent to the variable Number_Of_items . For example if the value for Number_Of_items was 6, I would want to create 6 arrays with names array1, array2 , array3 etc. if anyone could point me in the right direction it would be appreciated.

Building Numpy Array with a for loop Aug 11, 2020
r/learnpython
6y ago
How do i create an array in a while loop? Feb 29, 2024
r/learnpython
2y ago
for in statement to create a array Dec 6, 2024
r/learnpython
last yr.
For loop to create multiple objects Aug 3, 2019
r/learnpython
7y ago
Is it possible to create an array in python? May 2, 2024
r/learnpython
2y ago
More results from reddit.com
Discussions

Creating new array in for loop (Python) - Stack Overflow
I'm preparing a data set to run in the program rpy (R, which runs in Python) for statistical analysis. It looks like this: data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 15, 2013
Assign values to array during loop - Python - Stack Overflow
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, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Fast loop to create an array of values - Code Review Stack Exchange
I have a code that creates a 3D array of values from a minimum to a maximum in X and Z with constant Y. Right now I make it in normal Python, and then I transform it in a np.array. Is there a way to make it directly a NumPy array? How can I translate the code in NumPy to make it faster? targets = [] X = Y = 0 STEP_X = 0.1 STEP_Y = 0.2 MIN_X = X for ... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
April 14, 2017
How can I create an array in python using a for loop? - Stack Overflow
I have an array set out like this: ['age', 'height', 'weight'] and I need to "fill" the array with values from a list which contains objects with the values age, height and weight. For example: ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_loop_arrays.htm
Python - Loop Arrays
When you are using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements in the array. Inside the while loop, iterate over the array elements and manually update ...
๐ŸŒ
PyTutorial
pytutorial.com โ€บ make-an-array-in-python
PyTutorial | How to Create Array in Python Using For loop
June 10, 2023 - # Define an empty list my_array = [] # Use a for loop to iterate and append elements to the array for i in range(5): my_array.append(i) # Print the array print(my_array)
Find elsewhere
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ array โ€บ initialize-a-python-array
3 ways to initialize a Python Array - AskPython
January 16, 2024 - Python for loop and range() function together can be used to initialize an array with a default value. Syntax: [value for element in range(num)] Python range() function accepts a number as argument and returns a sequence of numbers which starts from 0 and ends by the specified number, incrementing by 1 each time. Python for loop would place 0(default-value) for every element in the array between the range specified in the range() function...
Top answer
1 of 1
4

You could use the np.fromiter function and Python's built in itertools.product to create the array you need:

Note: I'm assuming you're using Python 2.x based on your print statements.

import itertools
import numpy as np

product = itertools.product(xrange(X, X + 1000*STEP_X, STEP_X),
                            [Y],
                            xrange(Z, Z + 1000*STEP_Z, STEP_Z))

targets = np.fromiter(product)

This should be faster because it uses iterators instead of creating and allocating an entire list.


UPDATE

Here are some style pointers and other minor improvements that I could see. Most of these recommendations stem from PEP8, the official Python style guide, so if you need a reference for my suggestions, you can head over there.

  1. ALWAYS USE with. Whenever you deal with file access, use a with block as it is significantly less prone to user errors than using open() and close(). Luckily, you're code doesn't show the typical bug of not calling close() after an open(). However, its best to get into the habit of using with:

    with open('some_file.txt', 'r') as file: # Do stuff

  2. Use underscores_in_names when naming variables and functions. For the most part you do this. However, your function names could be updated.

  3. Function names should be verb-based as this style helps show that the function does something:

    # Currently...
    def XYZ2sRGB(...):
    
    # Better...
    def convert_to_RGB(...)
    

    A quick note: Typically I don't like using upper-case letters in anything except constants. However, because RGB is basically an acronym, capital letters seem appropriate.

  4. Speaking about upper-case letters, convention says that only constants should be capitalized in Python. This is relatively significant because convention is the only way we can 'define' constants in Python as there is no syntactic way to do so.

  5. Whitespace is your friend, however be careful not to overdo it. PEP8 actually calls extraneous whitespace a pet peeve. A few of the points mentioned in that section of PEP8 that are applicable are:

    # Bad                  # Good
    foo            = 1  |  foo = 1
    some_long_name = 0  |  some_long_name = 0
    --------------------+---------------------
    range (1000)        |  range(1000)
    --------------------+---------------------
    foo = ( x + 1 * 2 ) |  foo = (x + 1*2)
    

    The last example is really based on preference: simply use whitespace to group operations and operands together so that the calculation reads well.

  6. Parenetheses aren't required in if statements (unless they group conditionals together). You can remove almost all of yours.

  7. Use if ... elif ... when applicable. Take this group of statements:

    G = var_G * 255
    if (G > 255):
        G = 255
    if (G < 0):
        G = 0
    

    The second if will always be evaluated even if the first evaluated to True which means the second will evaluate to False. Because the two conditional are mutually exclusive, use and if-elif structure. Also, instead of basing your conditionals off of G (which requires a calculation beforehand) base your conditionals off of var_G:

    if var_G > 1:
        G = 255
    elif var_G < 0:
        G = 0
    else:
        G = var_G * 255
    

    This code only does the calculation if necessary and has the same number of possible comparisions (in the worst case).

  8. Use str.format instead of string concatenation. While whether string formatting performs better than string concatenation is up in the air, its more conventional (and, in my opinion, MUCH cleaner) to use str.format:

    with open(str(filename), "a") as f:
        f.write('<path d="M{} {} \n'.format(x*1/2.54*72, y*1/2.54*72)) #moveto
        f.write('    m {},0 \n'.format(-radius))
        f.write('    a {} 0 1,0 {},0 \n'.format(radius, radius, radius*2))
        f.write('    a {} 0 1,0 {},0 \n'.format(radius, radius, -radius*2))
        f.write('    " fill = "rgb({},{},{})"/> \n'.format(R, G, B))
    
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_array_iterating.asp
NumPy Array Iterating
It solves some basic issues which we face in iteration, lets go through it with examples. In basic for loops, iterating through each scalar of an array we need to use n for loops which can be difficult to write for arrays with very high ...
Top answer
1 of 3
1

You get a metar_dat array that is mostly 0 because it is the one you created at the last k iteration. It was len(stat_id) long (in the 1st dimensions) but you only inserted data for the last k. You threw away the results for the earlier k.

I would suggest collecting the data in a dictionary, rather than object array.

metar_dat = dict()  # dictionary rather than object array
for id in stat_id:
    # Bring all the data into one big array.
    data = np.column_stack([yr, month, day, time,temp, dwp])
    # should produce as (len(temp),6) integer array
    # or float is one or mo    for k in range(len(stat_id)):
    metar_dat[id] = data

If len(temp) varies for each id, you can't make a meaningful 3d array with shape (len(stat_id), len(temp), 7) - unless you pad every one to the same maximum length. When thinking about arrays, thing rectangles, not ragged lists.

A Python dictionary is a much better way of collecting information by some sort of unique id.

Object arrays let you generalize the concept of numeric arrays, but they don't give much added power compared to lists or dictionaries. You can't for example, add values across the 'id' dimension.

You need to describe what you hope to do with this data once you collect it. That will help guide our recommendations regarding the data representation.

There are other ways of defining the data structure for each id. It looked like yr, time, temp were equal length arrays. If they are all numbers they could be collected into an array with 6 columns. If it is important to keep some integer, while others are floats (or even strings) you could use a structured array.

Structured arrays are often produced by reading column data from a csv file. Some columns will have string data (ids) others integers or even dates, others float data. np.genfromtxt is a good tool for loading that sort of file.

2 of 3
0

You're setting your 2D array to zero inside your k-loop each time. Set it to zero (or empty, if all elements get filled, as in your case) once outside your nested loop, and you should be fine:

metar_dat = np.empty((len(stat_id),len(temp),7), dtype='object')
for k in range(len(stat_id)):
    for i in range(len(temp)):
        metar_dat[k,i] = np.dstack((stat_id[k], yr[i], month[i], day[i], time[i], temp[i], dwp[i]))
return metar_dat
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 54948120 โ€บ how-to-make-an-array-within-a-for-loop
python - How to make an array within a for loop? - Stack Overflow
Keqs = [] for i in range(len(DH4_3)): Keqs[i]=np.exp(-(DH4_3[i]-T4[i+127]*DS4)/(R*T4[i+127])) print(Keqs) # print out array after all items are added ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Basic Python #7 - For Loops and Arrays - YouTube
A simple introduction to for loops and arrays in Python.#python #pythontutorial #pythonprogramming
Published: October 22, 2022
๐ŸŒ
GitHub
hplgit.github.io โ€บ bumpy โ€บ doc โ€บ pub โ€บ sphinx-basics โ€บ ._basics001.html
Variables, loops, lists, and arrays
Running through multiple lists simultaneously is done with the zip construction: for e1, e2, e3, ... in zip(list1, list2, list3, ...): One may instead create a for loop over all the legal index values instead and index each array,
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 41308976 โ€บ is-it-possible-to-create-array-of-variables-in-a-python-for-loop
Is it possible to create array of variables in a python for loop? - Stack Overflow
The same with length, it is an int variable! ... Also, avoid using list as a variable name, as it shadows the built-in type. ... If you want all words in a list at the end you can use list variable declared at the start. If you want all the lengths stored in a list, change lengths = 0 for lengths = [] and append each length in the for loop (lengths.append(len(list[e]))
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ for-loops-in-python
For Loops in Python
February 1, 2020 - For Loop Statements Python utilizes a for loop to iterate over a list of elements. Unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.
๐ŸŒ
Dataquest
dataquest.io โ€บ home โ€บ blog โ€บ tutorial: advanced python for loops
Tutorial: Advanced Python for Loops
March 11, 2025 - Now, let's take a look at how for loops can be used with common Python data science packages and their data types. We'll start by looking at how to use for loops with numpy arrays, so let's start by creating some arrays of random numbers.