Laura Smith
Laura Smith

Reputation: 313

List index out of range error in the code

I have the following piece of code.

result = "1/1/2010|1/2/2111"
request = "1/1/1.3.4.5.6/1/1/127.0.0.1"

replylist = result.split("|")
finalresultlist = [
    f"{i.split('/')[2]}.{j.split('/')[2]}"
        for i in request
        for j in replylist \
        if (i.split("/")[1] == j.split("/")[1])
]

print(finalresultlist)

Note: The f"{i.split('/')[2]}.{j.split('/')[2]}" concatenates the "1.3.4.5.6" with the "2010" when there is a match if (i.split("/")[1] == j.split("/")[1]) based on the value in the index [1] after each of the result and request strings are split on the '|'.

I want to return a new string, which concatenates the 1.3.4.5.6 of request with 2010 of result to return a list which contains the string: ["1.3.4.5.6.2010"]

In my current code, I get the error "list out of range". I am unable to resolve this issue.

Any help is appreciated.

Upvotes: 0

Views: 78

Answers (2)

wjandrea
wjandrea

Reputation: 32944

Debugging

As molbdnilo commented,

request is a string, and iterating over it (for i in request) gives you one character at a time. It looks to me like you're trying to do too many things at once.

And if we look at the full error message including stack trace, we see a suggestion of that:

Traceback (most recent call last):
  File "/home/wjandrea/test.py", line 7, in <module>
    for i in request
  File "/home/wjandrea/test.py", line 9, in <listcomp>
    if (i.split("/")[1] == j.split("/")[1])
IndexError: list index out of range

Rearranging the code points to i.split("/")[1] being the problem.

Solution

Remove for i in request entirely, and substitute request for i.

finalresultlist = [
    f"{request.split('/')[2]}.{j.split('/')[2]}"
    for j in replylist
    if request.split("/")[1] == j.split("/")[1]
]

Output: ['1.3.4.5.6.2010']

Then there are some other improvements we could make, like better variable names and moving stuff out of the list comprehension.

replies = [i.split('/') for i in result.split("|")]
request_list = request.split('/')

final_result_list = [
    f"{request_list[2]}.{reply[2]}"
    for reply in replies
    if request_list[1] == reply[1]
]

print(final_result_list)

Upvotes: 2

user11751463
user11751463

Reputation:

Ok let's take baby steps.

result = "1/1/2010|1/2/2111"
result = result.split("|")

Now result is ['1/1/2010', '1/2/2111']

request = "1/1/1.3.4.5.6/1/1/127.0.0.1"
request = request.split("/")

Now request is ['1', '1', '1.2.3.4.5.6', '1', '1', '127.0.0.1'] So a simple way to get your desired result would be,

finalresult = "{}{}".format(request[2],result.split('/')[2])

I'm not sure of your looping logic, however, you should be able to use this code to programmatically generate more strings based on your business logic.

Upvotes: 2

Related Questions