Блог пользователя 123gjweq2

Автор 123gjweq2, история, 3 месяца назад, По-английски

I was solving a problem when I accidentally found this weird feature in python:

list1 = [1]
list1.append(list1)
print(list1[1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])

You can append a list to itself. This code prints 1.

list1 = []
list1.append(list1)
print(list1[0][0][0][0][0][0])

This will print [[...]]. I guess it prints this to show that the list tunnels on forever.

It makes sense but it still seems like an odd feature. I can't see how this would be useful.

  • Проголосовать: нравится
  • +24
  • Проголосовать: не нравится

»
3 месяца назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

Wow, Today I learnt a new thing.

»
3 месяца назад, # |
  Проголосовать: нравится +16 Проголосовать: не нравится

My guess it that when you append the list to itself , it appends a pointer to the list rather than the list itself , because of which the list has a element which points to itself , it is like a circular linked list i guess XD

»
3 месяца назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

.

»
3 месяца назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

You can accomplish something a bit similar in C++

#include <vector>
#include <cassert>

struct V : std::vector<V> {};

int main() {
    V tmp, &v = tmp.emplace_back();
    swap(tmp, v);

    assert(&v == &v[0]);
}

Bonus: this creates memory leak without any manual call to new/malloc.

»
3 месяца назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

.