Perplexityy Perplexityy - 6 months ago 20
Python Question

Appending two items in one list to a new list in Python

I have a list that currently looks like:

new_list = ['130 kms', '46 kms', '169 kms', '179 kms', '53 kms', '128 kms', '97 kms', '152 kms', '20 kms', '94 kms', '$266.07', '$174.14', '$187.01', '$488.69', '$401.53', '$106.88', '$398.33', '$493.87', '$205.43', '$248.14']


The first element, '130 kms' corresponds with the 11th element ('$266.07') and so on for the rest of the list. I'm trying to convert each of these relationships into a list, and append it to another list 'sort_list' forming a list of lists.

I'm attempting to do this with the code below.

**#new_list as written above**
sort_list = []

for l in range(len(new_list)):
for item in new_list:
sort_list.append(new_list[item]+[item+10]).split()


But it's giving me the error "list indices must be integers, not str". So does this mean that I cannot append strings to a list, or is there some kind of workaround?

This is the output I'm expecting:

[[130 kms, $266.07], [46 kms, $174.14], [169 kms, $187.01], [179 kms, $488.69], [53 kms, $401.53], [128 kms, $106.88], [97 kms, $398.33], [152 kms, $493.87], [20 kms, $205.43], [94 kms, $248.14]]

Answer
new_list = ['130 kms', '46 kms', '169 kms', '179 kms', '53 kms', '128 kms', '97 kms', '152 kms', '20 kms', '94 kms', '$266.07', '$174.14', '$187.01', '$488.69', '$401.53', '$106.88', '$398.33', '$493.87', '$205.43', '$248.14']

new_list1 = []

for x in new_list:
    try:
        new_list1.append([x,new_list[new_list.index(x)+10]])
    except:
        break
for x in new_list1:
    print (x)

Output

>>> 
['130 kms', '$266.07']
['46 kms', '$174.14']
['169 kms', '$187.01']
['179 kms', '$488.69']
['53 kms', '$401.53']
['128 kms', '$106.88']
['97 kms', '$398.33']
['152 kms', '$493.87']
['20 kms', '$205.43']
['94 kms', '$248.14']
>>>