Ethanol
Ethanol

Reputation: 370

How to make a list out of indexes of a list

I started a project where I turn a string into a list, and in the list I turn each index into another list. However, I ran into a problem. My code is below:

# Define the string
string = "Hello there!"

# Print string (Hello there!)
print(string)

# Define string_list and assign it to the list version of a string
string_list = list(string)

# Print string_list
print(string_list)
''' # ['H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '!'] '''

for i in string_list:
    i = list(i)

print(string_list)
''' ['H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '!'] '''

When I try to turn each index of the string_list into another list, it doesn't work. What I want is for the output of the final print of string_list to look like this:

[['H'], ['e'], ['l'], ['l'], ['o'], [' '], ['t'], ['h'], ['e'], ['r'], ['e'], ['!']]

Is there a way I can do this similar to my original method? Also, why does my original method not do what I want it to do? Thank you in advance.

Upvotes: 0

Views: 139

Answers (2)

Michael Swartz
Michael Swartz

Reputation: 858

# define the string
s1 = "Hello there!"

# holds nested lists
new_list = []

# print string
print(s1)
''' Hello there! '''

# convert string to a list
string_list = list(s1)

# print the list
print(string_list)
''' # ['H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '!'] '''

# load each element to list as a list
for i in string_list:
    new_list.append([i]) # <<<<< the '[i]' is important

print(new_list)
'''
[['H'], ['e'], ['l'], ['l'], ['o'], [' '], ['t'], ['h'], ['e'], ['r'], ['e'], ['!']]
'''

Upvotes: 0

Brad Solomon
Brad Solomon

Reputation: 40948

Is there a way I can do this similar to my original method?

Yes; two ways about this would be to use map() or a list comprehension.

>>> s = "Hi there"

>>> list(map(list, s))
[['H'], ['i'], [' '], ['t'], ['h'], ['e'], ['r'], ['e']]

>>> [[i] for i in s]  # or: [list(i) for i in s]
[['H'], ['i'], [' '], ['t'], ['h'], ['e'], ['r'], ['e']]

Also, why does my original method not do what I want it to do?

The problem lines are here:

for i in string_list:
    i = list(i)

As you can read more about in this question, assinging to i within the loop does not affect the elements of string_list themselves. To be specific, for i in string_list creates a new variable i at each turn of the loop, the last of which will still exist after the loop terminates. In short, it is good practice to avoid trying to modify the container (string_list) over which you're looping.

Upvotes: 1

Related Questions