Reputation: 1213
I'm trying to rearrange the following array of strings:
myString =['000', ['1', 'two', 'three'], ['1', 'b', 'c']]
So that myString2 looks like
myString2 = [['000', '1', 'two', 'three'], [['000', '1', 'b', 'c']]
Looking around for some ideas (e.g. here) I attempted the following loop:
myString2 = []
for i in range(0,len(myString)-1):
myString2 [i].append(myString[0])
myString2 [i].append(myString[i])
But I get an error which I don't really understand :
IndexError: list index out of range
I'm fairly new to python and wonder if there is perhaps a simpler way than my current idea, and if not, if someone could kindly explain what is preventing the loop from running.
Upvotes: 0
Views: 192
Reputation: 11573
You were close with your script, this works:
myString =['000', ['1', 'two', 'three'], ['1', 'b', 'c']]
myString2 = []
for i in range(1,len(myString)):
myString2.append(myString[0])
myString2.append(myString[i])
What was wrong?
myString2[i].append
attempts to append something at myString
, index i
, so at first iteration it tries to access myString[0]
but myString
is still empty, that causes the out of range error. Instead use append
just on the list and it will add the element at the last positionrange(1,...
range(1,5)
is [1,2,3,4]
-> you don't need to substract 1Upvotes: 2
Reputation: 22953
Instead of trying to use the first list to hold the string 0000
, why not put it in a constant instead
MAGIC_STRING = '0000'
and then simply use the constant to create the new, modified sublists:
myString = [['1', 'two', 'three'], ['1', 'b', 'c']]
myString2 = [[MAGIC_STRING] + el for el in myString]
Upvotes: 0
Reputation: 140186
The snippet of code you provided cannot work because of variable names, so I won't try to explain you what's wrong with it further.
That said, those problems can be easily done in one-liners using list comprehensions:
myString =['000', ['1', 'two', 'three'], ['1', 'b', 'c']]
new_string = [[myString[0]]+s for s in myString[1:]]
print(new_string)
just create a new list of lists, with the first element as head, and the rest as tail.
Results as:
[['000', '1', 'two', 'three'], ['000', '1', 'b', 'c']]
Upvotes: 1