Skip to content

Instantly share code, notes, and snippets.

@pn11
Created August 14, 2019 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pn11/fc12cd366f9c75727939b34c4c4d2663 to your computer and use it in GitHub Desktop.
Save pn11/fc12cd366f9c75727939b34c4c4d2663 to your computer and use it in GitHub Desktop.
Creating two-dimensional array in Python. Result -> https://ideone.com/M2TpNg
li = [[]] * 2
print(li)
li[0].append(1)
print(li)
print(id(li[0]))
print(id(li[1]))
li2 = [[] for _ in range(2)]
print(li2)
li2[0].append(1)
print(li2)
print(id(li2[0]))
print(id(li2[1]))
# Result in Ideone
# https://ideone.com/M2TpNg
@pn11
Copy link
Author

pn11 commented Aug 14, 2019

[[]]*2 のように2次元配列を作ると、[[],[]] の中の2つの [] が同じ実体になっていて、片方に append すると両方に要素が追加される。
リスト内包表記でつくればこのようなことはない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment