0

I am wondering why this piece of code:

wordlist = ['cat','dog','rabbit']
letterlist=[]
for aword in wordlist:
    for aletter in aword:
        if aletter not in letterlist:
            letterlist.append(aletter)
print(letterlist)

prints ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

while this code:

wordlist = ['cat','dog','rabbit']
letterlist=[]
for aword in wordlist:
    for aletter in aword:
        letterlist.append(aletter)
print(letterlist)

prints ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

I don't understand how the code is being computed and doesn't spell out all of 'rabbit' and/or why it spells out 'r', 'b', 'i'? Anyone know what's going on?

faceless
  • 436
  • 1
  • 4
  • 11
  • 1
    the first code checks to see whether the letter is already in the letter list. If it is, it doesn't add to the list. So the 'a', 'b', 't' of 'rabbit' don't show up, because they're already in the list (from 'cat' and the first 'b' of 'rabbit'). – Stidgeon Jan 17 '16 at 03:25

2 Answers2

1

You are adding each unique letter to letterlist with this if block:

if aletter not in letterlist:
    letterlist.append(aletter)

If the letter has already been seen, it does not get appended again. That means the second time you see a (in 'rabbit'), the second b (in 'rabbit') and the second and third time you see t, they aren't added to the list.

Andy
  • 49,085
  • 60
  • 166
  • 233
0

This part of the code if aletter not in letterlist: checks if the letter has already been added to the list. If it does, you wont add it again.

So basically you wont add any repeated characters. That's why the output is ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] . No repeated letters there.

The second piece of code just iterates the whole list and appends to letterlist no matter what. That's why all letters are added, and you get ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't'] as result.

rafaelc
  • 57,686
  • 15
  • 58
  • 82