1

I have a list (list1) as follows:

[0, 1, 2]

I want to prepend each element to a list (list2) of strings:

['Start|983471|String1|True\n',
 'Start|983472|String2|True\n',
 'Start|983473|String3|True\n']

to give:

['0|Start|983471|String1|True\n',
 '1|Start|983472|String2|True\n',
 '2|Start|983473|String3|True\n']

My code:

Finallist = []
x=0
while x < len(list1):
    for line in list2:
        Finallist.append("|".join((str(list1[x]),line)))
    x+=1

This gives back 9 lines. What's wrong? I would expect each item to be added.

3 Answers 3

3

The problem with your code is that you effectively have 2 loops, one that goes through x from 0 to the length of the list and another one that goes through each line in the list so it looks like:

for x in range(len(list1)):
    for line in list2:
        Finallist.append("|".join((str(list1[x]),line)))

So you will be appending every line, on each iteration through list1. You probably wanted something like:

for x in range(len(list1)):
    Finallist.append("|".join((str(list1[x]),list2[x])))

Here's how to do it more compactly with a list comprehension:

>>> list1 = [0, 1, 2]
>>> list2 = ['Start|983471|String1|True\n',
 'Start|983472|String2|True\n',
 'Start|983473|String3|True\n']
>>> ['{0}|{1}'.format(num, s) for num, s in zip(list1, list2)]
['0|Start|983471|String1|True\n', '1|Start|983472|String2|True\n', '2|Start|983473|String3|True\n']

I observe you are just using the index of each line, so instead you could use:

['{0}|{1}'.format(i, s) for i, s in enumerate(list2)]
Sign up to request clarification or add additional context in comments.

Comments

2

enumerate and zip will do the work:

list1 = [0, 1, 2]

data1 = ['Start|983471|String1|True\n',
 'Start|983472|String2|True\n',
 'Start|983473|String3|True\n']

for i, (line, num) in enumerate(zip(data1[:], list1)):
    data1[i] = str(num) + '|' + line

print(data1)

Output:

['0|Start|983471|String1|True\n', '1|Start|983472|String2|True\n', '2|Start|983473|String3|True\n']

Comments

0

don't use for loop .. .while loop is sufficient..

list1=['Start|983471|String1|True\n', 'Start|983472|String2|True\n', 'Start|983473|String3|True\n']
list2=['1','2','3']   
Finallist = []
x=0
while x < len(nk):
    Finallist.append(str(list2[x])+'|'+list1[x])
    x+=1

1 Comment

An index for both, that's where i went wrong. All suggestions very good. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.