Home > Software engineering >  why does my for loop split words into individual letters during iteration in python
why does my for loop split words into individual letters during iteration in python

Time:02-15

I tried to pass the items in the dictionary below into a list birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4', "Zeke": "September 11", "Matt": "June 30"} I used two methods Method 1

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4', "Zeke": "September 11", "Matt": "June 30"}
dict_Birthdays = []

for k in birthdays.keys():
    dict_Birthdays  = k
print(dict_Birthdays)

method 1 output = ['A', 'l', 'i', 'c', 'e', 'B', 'o', 'b', 'C', 'a', 'r', 'o', 'l', 'Z', 'e', 'k', 'e', 'M', 'a', 't', 't']

method 2

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4', "Zeke": "September 11", "Matt": "June 30"}
dict_Birthdays = []

for k in birthdays.keys():
    dict_Birthdays.append(k)
print(dict_Birthdays)

Method 2 output : ['Alice', 'Bob', 'Carol', 'Zeke', 'Matt']

I'd like to know in lay and detailed terms why method 1 has split my items into individual letters

CodePudding user response:

dict_Birthdays = k is like dict_Birthdays.extend(k). That expects something to be a sequence, and appends each element to the list. So it's equivalent to:

for letter in k:
    dict_Birthdays.append(letter)

This adds each letter as a separate list element.

CodePudding user response:

Your two examples are very different. In the first example, dict_Birthdays = k is equivalent to dict_Birthdays.extend(k), but your second example uses dict_Birthdays.append(k). The extend() method adds the elements of the given iterable to the list. In contrast, the append() method adds the given element directly to the list.

  • Related