käyrätorvi
käyrätorvi

Reputation: 381

How can I add different elements to a list in a list? Python 3

f = open("sonad.txt",encoding="utf-8")
c = f.readlines()
blokk = [[]] * 15
for read in c:
    length = len(read.strip())
    blokk[length].append(read.strip())

sonad.txt has just some random words and I would like to put them in an order like so:

All the words, that are 1 letter long go to blokk[1] 2 letters long go to blokk[2] And so on...

But what my current code does is that it adds an element to allL block[x] so that blokk[1] blokk[2] blokk[3] ..... are all the same.

Upvotes: 1

Views: 133

Answers (2)

mgilson
mgilson

Reputation: 310187

 blokk = [[]]*15

creates 15 references to the same list. So, if you append to blokk[0] or block[1], those changes will be reflected in either list since they're the same list.

Perhaps a better data structure here is a defaultdict:

from collections import defaultdict
d = defaultdict(list)
with open('sonad.txt', encoding='utf-8') as fin:
    for line in fin:
        stripped = line.strip()
        d[len(stripped)].append(stripped)

print(sorted(d.items()))

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1124558

The line blokk = [[]] * 15 creates a list that has the same empty list in it 15 times.

You want to use a list comprehension instead:

blokk = [[] for _ in range(15)]

Try it out for yourself:

>>> blokk = [[]]*15
>>> blokk
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> blokk[0].append(1)
>>> blokk
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
>>> blokk = [[] for _ in range(15)]
>>> blokk
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> blokk[0].append(1)
>>> blokk
[[1], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

Upvotes: 7

Related Questions