Python Forum

Full Version: Creating list out of the first letter of every word in a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I’m trying to create a list for every first letter in the given string.

Here is my script:
mystring = "Secret agents are super good at staying hidden."
words = mystring.split()
for char in words:
    first_char_list = char[0]
    print(list(first_char_list))
My expected output:

Quote:['S', 'a', 'a', 's', 'g', 'a', 's', 'h']

My actual output:
Quote:['S']
['a']
['a']
['s']
['g']
['a']
['s']
['h']

My loop creates a new list for every item. That’s not what I want. I figure I need to append every item each time when char completes its iteration. I’ve kind of done that already, but evidently I’m not doing it properly. I am not sure what I am doing wrong.

For my future reference, this forum thread refers to Task #3 in Jose Portilla’s so called 04-Field-Readiness-Exam-2 in his “Narrative Journey” Udemy Python course material (on GitHub: Pierian-Data/Python-Narrative-Journey).

Thanks for your attention.
for word in words:
    # get the first letter of the word
Look up adding to a list https://www.google.com/search?q=python+a...e&ie=UTF-8 You create a new string (not list) on every pass through the for. You want to create a list first, and then add the first letter to the list on every pass through the for.
Desired result can be achieved also this way:

>>> mystring = "Secret agents are super good at staying hidden."
>>> [word[0] for word in mystring.split()]
['S', 'a', 'a', 's', 'g', 'a', 's', 'h']
(Oct-05-2018, 03:08 AM)wavic Wrote: [ -> ]
for word in words:
    # get the first letter of the word
This! With this advice I promptly adjust my script so it looks like this:

mystring = "Secret agents are super good at staying hidden."
words = mystring.split()
first_char_list = []
for char in words:
    first_char_list.append(char[0])
print(first_char_list)
My script now produces the desired output!! Thanks, @wavic.

(Oct-05-2018, 05:44 AM)perfringo Wrote: [ -> ]Desired result can be achieved also this way:
>>> mystring = "Secret agents are super good at staying hidden."
>>> [word[0] for word in mystring.split()]
['S', 'a', 'a', 's', 'g', 'a', 's', 'h']
This is list comprehension format. In the Udemy course I’m taking, the original task was to use list comprehension but I find it hard to read so I decided to complete the exercise without list comprehension by just using a regular for loop.

(Oct-05-2018, 04:07 AM)woooee Wrote: [ -> ]Look up adding to a list https://www.google.com/search?q=python+a...e&ie=UTF-8 You create a new string (not list) on every pass through the for. You want to create a list first, and then add the first letter to the list on every pass through the for.
The first search result when you Google, ‘python adding to a list’, is an official doc by Google titled, “Python Lists”. It’s helpful but there is one recurring theme through out the doc which to me looks like an enormous mistake. Take a look at this teachable code snippet from that webpage:
list = ['larry', 'curly', 'moe']
list.append('shemp')         ## append elem at end
list.insert(0, 'xxx')        ## insert elem at index 0
list.extend(['yyy', 'zzz'])  ## add list of elems at end
print list  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly')    ## 2
In every single line, the author of the doc creates or refers to a variable named, list. What doesn’t make sense to me is that list is a reserved keyword in Python in general, correct? When I type just list into my Jupyter Notebook, it highlights as green as if to cast a variable into a list. So my non-rhetorical question for anyone still reading this forum post is: How is Google able to get away with using list as a variable???
(Oct-05-2018, 06:27 PM)Drone4four Wrote: [ -> ]...
This is list comprehension format. In the Udemy course I’m taking, the original task was to use list comprehension but I find it hard to read so I decided to complete the exercise without list comprehension by just using a regular for loop.

List comprehension is fundamental to mastering Python. Maybe that definition will help - list comprehension is a drill-down of a regular loop where the value appended to the list is placed before the loop.

Take a look at this example - building a list of even values from a list of numbers. This is how you will do it in a loop
evens = []
for num in num_list: # <---- loop expression
    if num % 2 == 0: # <---- condition (predicate)
        evens.append(num) # <---- appended value
And now pay attention to the list comprehension form - same code sans columns, just the value moved before the loop.
evens = [
num # <---- appended value
for num in num_list # <---- loop expression
    if num % 2 == 0 # <---- condition (predicate)
]
Is it easier now?

(Oct-05-2018, 06:27 PM)Drone4four Wrote: [ -> ]The first search result when you Google, ‘python adding to a list’, is an official doc by Google titled, “Python Lists”. It’s helpful but there is one recurring theme through out the doc which to me looks like an enormous mistake. Take a look at this teachable code snippet from that webpage:
list = ['larry', 'curly', 'moe']
list.append('shemp')         ## append elem at end
list.insert(0, 'xxx')        ## insert elem at index 0
list.extend(['yyy', 'zzz'])  ## add list of elems at end
print list  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly')    ## 2
In every single line, the author of the doc creates or refers to a variable named, list. What doesn’t make sense to me is that list is a reserved keyword in Python in general, correct?

Actually, list is a built-in function (good catch) so naming a variable list shadows that function (you cannot assign a value to a keyword).

Not everything you find on the web is of good quality, and sometimes shitty resources hide behind a great name. This resource - besides teaching bad practice - is also pitifully outdated - Python2. I usually use time filter in my searches - that helps.

The last but not the least - functional programming version of solution
Output:
In [2]: from operator import itemgetter In [3]: list(map(itemgetter(0), mystring.split())) Out[3]: ['S', 'a', 'a', 's', 'g', 'a', 's', 'h']

Wow, this developers.google.com crap is actually
Quote:Last updated May 18, 2018.
Doh