Golf-FAQ.com

how to iterate through 2d array python code golf

by Lesley Reilly Published 2 years ago Updated 1 year ago
image

How to iterate through a 2D list?

In the case of 2D lists, each element is another list. Here’s an example: This 2D list also has 3 elements, but each of those elements is a list itself. Let’s build on the list examples above. To iterate through the 1D list [0, 1, 4] and print each element separated by a space, you could use the following code:

How do you iterate through a list of elements in Python?

First, the list is assigned to a variable called data. Then we use a for loop to iterate through each element in the range of the list. Unless we specify a starting index for the range, it defaults to the first element of the list.

What is a 2D list in Python?

In Python, they are a type of data, denoted by brackets. For example, [0, 1, 4] is a list with 3 elements. This is referred to as a one-dimensional list because each element of the list is a number. In the case of 2D lists, each element is another list. Here’s an example:

What is the range of a for loop in Python?

The for loop goes up to the ending index, but it doesn’t include that index. len (data) is the count of elements in our list. We have 3 elements, so our range goes from index 0 to index 2, just like we want.

image

Rules

Input will be a 2D array of integers and a 1-indexed integer. This integer will represent the row to be sorted if the number is positive, or the column to be sorted if the number is negative (or the other way round you want).

Explanation

y % Implicit inputs: number n, matrix M. Duplicate from below: pushes n, M, n 0> % Greater than 0? XH % Copy into clipboard H ? % If true ! % Transpose matrix.

How it works?

A more elaborate and visual explanation can be found in the linked answer.

image
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9