Python Forum
Creating list out of the first letter of every word in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating list out of the first letter of every word in a string
#1
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.
Reply
#2
for word in words:
    # get the first letter of the word
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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.
Reply
#4
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']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
(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???
Reply
#6
(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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Retrieve word from string knob 4 432 Jan-22-2024, 06:40 PM
Last Post: Pedroski55
  extract substring from a string before a word !! evilcode1 3 491 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,497 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  find some word in text list file and a bit change to them RolanRoll 3 1,482 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  Isolate a word from a long string nicocorico 2 1,501 Feb-25-2022, 01:12 PM
Last Post: nicocorico
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,883 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  change string in MS word Mr_Blue 8 3,217 Sep-19-2021, 02:13 PM
Last Post: snippsat
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Creating new column with a input string drunkenneo 2 2,196 Apr-14-2021, 08:10 AM
Last Post: drunkenneo
  Trying to get the first letter of every word in a list DanielCook 2 2,102 Jan-05-2021, 05:06 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020