8

I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change.

n is my list of websites h is "http"

for p in n:
    if p[0]!="h":
        p= h+ p
    else:
        continue
return n

when i return the list, it returns my original list and with no appending of the "http". Can somebody help me?

1
  • might consider checking past the first character if your list has websites that start with 'h', but aren't 'http' Commented Oct 20, 2012 at 15:12

4 Answers 4

15

This could also be done using list comprehension:

n = [i if i.startswith('h') else 'http' + i for i in n]
Sign up to request clarification or add additional context in comments.

Comments

3

You need to reassign the list item -- strings are immutable, so += is making a new string, not mutating the old one. I.e.:

for i, p in enumerate(n):
  if not p.startswith('h'):
    n[i] = 'http' + p

Comments

0
n = [{True: '', False: 'http'}[p.startswith('h')] + p for p in n]

Don't really do this. Although it does work.

3 Comments

Probably because it's an amusingly hacky way of doing it.
Just FYI: Python has if-else expressions now, so the dict/sequence/and-or hacks to simulate them aren't necessary anymore. See Max S.'s answer for a de-hackified version of yours.
@Laurence: Their "misorder" compared to the C ternary operator makes me avoid them because I don't need inexperienced Python programmers coming from other languages tripping over them. Not that it's a reason to use a dict for it though...
0
>>> n=["abcd","http","xyz"]

>>> n=[x[:1]=='h' and x or 'http'+x for x in n]

>>> n
['httpabcd', 'http', 'httpxyz']

4 Comments

Will fail for an empty string. But hopefully there won't be too many of those.
have you tried? :-) [:1] is used instead of [0] for that case.
No, I thought I saw a problem with the logic, but I was mistaken in this particular case. If the condition had been x[:1]!='h' then it would have failed.
Yes :-) thats how and or working as you know, I intentionally use =='h' for this case, to avoid '' going to and part

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.