Cara menggunakan python 2d list indexing


Two dimensional array is an array within an array. It is an array of arrays. In this type of array the position of an data element is referred by two indices instead of one. So it represents a table with rows an dcolumns of data.

Table of Contents

  • Accessing Values
  • Inserting Values
  • Updating Values
  • Deleting the Values
  • Can list be two
  • Is a 2D array a list?
  • How do I view a 2D list in Python?
  • Are Python lists one dimensional?

In the below example of a two dimensional array, observer that each array element itself is also an array.

Consider the example of recording temperatures 4 times a day, every day. Some times the recording instrument may be faulty and we fail to record data. Such data for 4 days can be presented as a two dimensional array as below.

Day 1 - 11 12 5 2 
Day 2 - 15 6 10 
Day 3 - 10 8 12 5 
Day 4 - 12 15 8 6 

The above data can be represented as a two dimensional array as below.

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

Accessing Values

The data elements in two dimesnional arrays can be accessed using two indices. One index referring to the main or parent array and another index referring to the position of the data element in the inner array.If we mention only one index then the entire inner array is printed for that index position.

Example

The example below illustrates how it works.

from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

print(T[0])

print(T[1][2])

Output

When the above code is executed, it produces the following result −

[11, 12, 5, 2]
10

To print out the entire two dimensional array we can use python for loop as shown below. We use end of line to print out the values in different rows.

Example

from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
for r in T:
   for c in r:
      print(c,end = " ")
   print()

Output

When the above code is executed, it produces the following result −

11 12  5 2 
15  6 10 
10  8 12 5 
12 15  8 6 

Inserting Values

We can insert new data elements at specific position by using the insert() method and specifying the index.

Example

In the below example a new data element is inserted at index position 2.

from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

T.insert(2, [0,5,11,13,6])

for r in T:
   for c in r:
      print(c,end = " ")
   print()

Output

When the above code is executed, it produces the following result −

11 12  5  2 
15  6 10 
 0  5 11 13 6 
10  8 12  5 
12 15  8  6 

Updating Values

We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index.

Example

from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

T[2] = [11,9]
T[0][3] = 7
for r in T:
   for c in r:
      print(c,end = " ")
   print()

Output

When the above code is executed, it produces the following result −

11 12 5  7 
15  6 10 
11  9 
12 15 8  6 

Deleting the Values

We can delete the entire inner array or some specific data elements of the inner array by reassigning the values using the del() method with index. But in case you need to remove specific data elements in one of the inner arrays, then use the update process described above.

Example

from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

del T[3]

for r in T:
   for c in r:
      print(c,end = " ")
   print()

Output

When the above code is executed, it produces the following result −

11 12 5 2 
15 6 10 
10 8 12 5 

Python 2D List ExamplesCreate a list of lists, or a 2D list. Append empty lists to a list and add elements.

2D list. Programs often must model 2 dimensions, not just one. In a Python list we can place other lists: this creates a 2D representation of objects.

Cara menggunakan python 2d list indexing

Python list notes. We can access elements on each list with an index—we must specify the X and Y positions. To construct a 2D list, we can use append() or an initializer.

List, strings

First example. We create an empty list and add empty lists to it with append(). We can construct any rectangular (or jagged) list this way. In this example we build a 2 by 2 list.

Step 1 We first create an empty list with the empty square brackets. Then we call the append method and add 2 empty lists.

Step 2 We access each sub-list and call append on it. This appends to the inner lists.

Step 3 We display the element at indexes 0, 0 and this value is 1. With the print() method we can display the entire list contents.

Step 4 This loop can iterate rows and columns in the 2D list. Nested for-loops loop over rows and columns.

# Step 1: create a list. # ... Append empty lists in first two indexes. elements = [] elements.append([]) elements.append([]) # Step 2: add elements to empty lists. elements[0].append(1) elements[0].append(2) elements[1].append(3) elements[1].append(4) # Step 3: display top-left element. # ... Display entire list. print(elements[0][0]) print(elements) # Step 4: loop over rows. for row in elements: # Loop over columns. for column in row: print(column, end="") print(end="\n")

1 [[1, 2], [3, 4]] 12 34

Jagged lists. The term "jagged" implies that sub lists have uneven lengths. Here we create a list of 2 lists—one of length 2, the other of length 5. We display their lengths.

Info This is a list of lists, not exactly a 2D list. It does not need to be rectangular—some lists can be longer than others.

Tip All the methods on list, including "len" and "in," work on nested lists. But they consider only one sub-list at a time.

Len

Warning For performance, nested lists are not optimal. An array is faster than a list.

Array

# A jagged list. values = [[10, 20], [30, 40, 50, 60, 70]] for value in values: # Print each row's length and its elements. print(len(value), value)

2 [10, 20] 5 [30, 40, 50, 60, 70]

Flattened. It is possible to index into a 1D array as though it is two-dimensional. We add the first coordinate, "x," and then multiply the second "y" coordinate by the length.

Index The multiplication of the coordinates returns a single integer for a 2D point.

Here We define get_element and set_element methods. We compute indexes based on an "x" and "y" coordinate pair.

def get_element(elements, x, y): return elements[x + (y * 4)] def set_element(elements, x, y, value): elements[x + (y * 4)] = value # Create a list of 16 elements. elements = [] for i in range(0, 16): elements.append(0) i = 0 for x in range(0, 4): for y in range(0, 4): # Set each element in the flattened list. set_element(elements, x, y, i) i += 1 # Print some elements. print(get_element(elements, 0, 0)) print(get_element(elements, 1, 1)) print(get_element(elements, 3, 3))

0 5 15

Benchmark, nested list. Suppose it is simple to change a nested list to a flattened, 1D list. This will likely result in a performance increase.

Version 1 This version of the code accesses an element in a nested list—so it accesses 2 elements total.

Version 2 This code accesses the flattened list, using an expression to compute the correct index.

Result Accessing the element at position coordinates 1, 2 is slightly faster in the flattened list.

import time # Nested, 3x2. nested_list = [] nested_list.append([10, 20, 30]) nested_list.append([40, 50, 60]) # Flattened, 3x2. flat_list = [10, 20, 30, 40, 50, 60] # Test the two lists. print(nested_list[1][2]) print(flat_list[1 + (2 * 2)]) print(time.time()) # Version 1: access element in nested list. for i in range(0, 100000000): if nested_list[1][2] != 60: print(False) print(time.time()) # Version 2: access element in flattened list. for i in range(0, 100000000): if flat_list[1 + (2 * 2)] != 60: print(False) print(time.time())

60 60 1420077374.795 1420077375.334: Nested list, 0.539 s 1420077375.794: Flat list, 0.460 s [PyPy]

2D array. Python supports a special "array" from the array module. An integer array is more compact in memory than an integer list. We can create a flattened 2D array.

2D Array

A review. Sometimes a 2D list is helpful in programs. For a simple or small coordinate system or grid, nested lists can be useful. They are flexible. The syntax is clear.

Larger data sizes. For larger or more complex requirements, this approach is not ideal. Another data structure, like an array, is a better choice at this scale.

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on 2/24/2022 (edit).

Can list be two

A list keeps track of multiple pieces of information in linear order, or a single dimension. However, the data associated with certain systems (a digital image, a board game, etc.) lives in two dimensions.

Is a 2D array a list?

The most common and the simplest form of Multidimensional Array Lists used is 2-D Array Lists.

How do I view a 2D list in Python?

Use list indexing to access elements in a 2D list. Use the list indexing syntax a_2d_list[x][y] to access an element at index y in the nested list at index x .

Are Python lists one dimensional?

The user first inputs a list, and I convert it to array. Python lists are one dimensional only.