Derp
Derp

Reputation: 143

Split a list of strings into their individual characters Python

Let's say I have a list:

list = ['foo', 'bar', 'bak']

I want to split these strings into their characters so I can assign values to each character (I.E. f = 5, o = 15, and so on).

How might I decompose these lists? I was thinking of turning each element into its own list, and referring to each element as an item of that list, but I am not sure how to go about doing that.

Upvotes: 3

Views: 11035

Answers (5)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can use one line solution :

list1 = ['foo', 'bar', 'bak']
print([j for i in list1 for j in i])

result :

['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'k']

Upvotes: 0

akhilesh.saipangallu
akhilesh.saipangallu

Reputation: 49

Join the entire list to each character

my_list = ['foo', 'bar', 'bak']

result = list(''.join(my_list))

result

['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'k']

now you can iterate through result to assign value to each character

Upvotes: -1

Gerges
Gerges

Reputation: 6499

Maybe that's what you want to convert into list of characters:

l = ['foo', 'bar', 'bak']

list(''.join(l))

Upvotes: 0

Kirshan Murali
Kirshan Murali

Reputation: 1

If This Is What Your Looking For Here You Go:

listItems = ['foo', 'bar', 'bak']
listLetter = []
myDictionary = {}

for item in listItems:
    for letter in item:
        listLetter.append(letter)

myDictionary['f'] = 5

print myDictionary

Upvotes: 0

Acontz
Acontz

Reputation: 481

Strings are iterable in Python, so you can just loop through them like this:

list = ['foo', 'bar', 'bak']

for item in list:
    for character in item:
        print(character)

Upvotes: 4

Related Questions