Thomas
Thomas

Reputation: 1

Python: Filling a list from another list

I am trying create a new list ("newList") from items an existing list ("letterList"). The catch is, the the new list may start on any item in the existing list, depending on the argument passed to the function ("firstLetter"):

def makeNewList(firstLetter):
    letterList=["A","B","C"]
    newList=[]

    # get index of argument (firstLetter) 
    for i in [i for i,x in enumerate(letterList) if x==firstLetter]:
        index=i

    # fill newList from cycling through letterList starting at index position 
    for j in range(10):
        if index==3:
            index=0
        newList[j]=letterList[index]
        index=index+1

makeNewList("B")

I was hoping this would give me newList["B","C","A","B","C","A","B","C","A"] but I get IndexError: list assignment index out of range referencing this line: newList[j]=letterList[index]

Upvotes: 0

Views: 4088

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122036

You can't assign by index to a list index that doesn't yet exist:

>>> l = []
>>> l[0] = "foo"

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    l[0] = "foo"
IndexError: list assignment index out of range

Instead, append to the end of newList. Also, you need to return the result:

def makeNewList(firstLetter):
    letterList=["A","B","C"]
    newList=[]

    # get index of argument (firstLetter) 
    for i in [i for i,x in enumerate(letterList) if x==firstLetter]:
        index=i

    # fill newList from cycling through letterList starting at index position 
    for j in range(10):
        if index==3:
            index=0
        newList.append(letterList[index]) # note here
        index=index+1

    return newList # and here

Here is a more Pythonic implementation:

def make_new_list(first_letter, len_=10, letters="ABC"):
    new_list = []
    start = letters.index(first_letter)
    for i in range(start, start+len_):
        new_list.append(letters[i % len(letters)])
    return new_list

Upvotes: 1

Andrew Johnson
Andrew Johnson

Reputation: 3186

Use the .append function to add to the end of a list.

def makeNewList(firstLetter):
    letterList=["A","B","C"]
    newList=[]

    # get index of argument (firstLetter) 
    for i in [i for i,x in enumerate(letterList) if x==firstLetter]:
        index=i

    # fill newList from cycling through letterList starting at index position 
    for j in range(10):
        if index==3:
            index=0
        newList.append( letterList[index] )
        index=index+1
    return newList

print(makeNewList("B"))

Upvotes: 1

Related Questions