1

Say I have the following list of words

words = ["arid", "dash", "drain", "thread"]

and an empty list of lists:

a=[[]]*7

I want to place these words in the list of lists such that the length of each word determines the position of the list they are appended to.

For example, because "arid" has length 4, it would go on:

a=[[],[],[],[],["arid"],[],[]]

"dash" has length 4 as well, so it would go on:

a=[[],[],[],[],["arid", "dash"],[],[]]

but "drain" has length 5, so it would go on:

a=[[],[],[],[],["arid", "dash"],["brain"],[]]

and "thread" has length 6, so it would go on:

a=[[],[],[],[],["arid", "dash"],["brain"],["thread"]]

I attempted the following code:

A = [[]]*7 #7 is len(thread)+1. it's not hard coded in my implementation

for word in words:
    size=len(word)
    A[size].append(word)
print(A)

when I run this I get:

>>[['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread']]

which makes no sense. everytime I append, the word gets appended to every single list on the list of lists. What am I doing wrong? can someone help?

canecse
  • 1,772
  • 3
  • 16
  • 20
  • 2
    Effectively `[[]]*7` creates 7 pointers to the same list object, hence the behavior you see. The solutions from @student, for example, creates 7 independent lists, which is what you need. – sal Sep 22 '18 at 02:00

1 Answers1

1

You need to change to A = [[]for _ in range(7)]. You can try as following:

A = [[]for _ in range(7)] #7 is len(thread)+1. it's not hard coded in my implementation

for word in words:
    size=len(word)
    A[size].append(word)
print(A)

Output:

[[], [], [], [], ['arid', 'dash'], ['drain'], ['thread']]
niraj
  • 17,498
  • 4
  • 33
  • 48