Multidimensional Array of Lists in Python


I participated in Codeforces online contest yesterday and was trying to solve this problemusing DFS (Depth-First-Search). I got somehow stuck in the WA3 (Wrong Answer Test 3). I checked carefully again and again but sadly I couldn’t figure out why.

The connectivity graph is represented using adjacent list, not matrix, because the number of nodes is large and it will cause memory limit error. I use the following two dimensional array of list in Python but at first I didn’t get it right, as one of the common mistakes that beginners might make.

arr = [[]] * n

Instead of real two-dimensional array of elements, it is producing the array of identical-referenced element. The below is the correct way to do it, by using a loop inside the list creation. The sample principle applies to multi-dimensional array creation in Python.

arr = [[] for _ in xrange(n)]

The below quickly illustrates the difference.

python Multidimensional Array of Lists in Python beginner codeforces implementation programming languages python tricks

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
238 words
Last Post: Codeforces: B. Roma and Changing Signs
Next Post: Codeforces: A. Beautiful Matrix

The Permanent URL is: Multidimensional Array of Lists in Python

2 Comments

  1. sunkehappy
  2. chenpeng

Leave a Reply