I want to save elements of a list as a whole in a new list.
My new task is to transform nested lists into a flat one. My plan was to take out the elements of each list and save them into a variable. And in the end to put the variables together, so that there is just a flat list at the end.
I have two problems:
The index-3 element (
'99999'
) isn't saved as a whole in the list of the new variable. This problem is the topic of this question.I cannot separate the nested list
[66, 77, 88]
from the higher list ['4', '5',[]], but this is not the topic of this question
So here is the code of the nested list and of my if statement:
nested_list = ['1', '2', '3', '99999',['4', '5',[66, 77, 88]]]
y = []
for i in nested_list:
if type(i) != (list or tuple):
y += i
print(y)
I want the index=3 element (the string '99999'
) be saved in the variable y
as a whole string and not split into the single parts '9', '9', '9', '9', '9'
I want:
print(y)
['1', '2', '3', '99999']
I get:
print(y)
['1', '2', '3', '9', '9', '9', '9', '9']
I can't solve the problem with saving into a string (y = ' '
), because than I get the result:
print(y)
12399999
and if I would transform the string to a list
y = list(y)
I get the same unwanted result
['1', '2', '3', '9', '9', '9', '9', '9']
I think the solution lies in the action code after the if-statement
y += i
Is there a command, which takes the whole element into y
? I tried y += sum(i)
but of course this didn't work, because
it adds up all numbers like int, floats, etc.., not strings
I don't need to add
9+9+9+9+9=45
, but I need just the whole string in my new listy
.