0

Element3 of each list is a list (in brackets). I want element3 to be a string 'store1.txt' not ['store1.txt'].

store_list = [["Freds", "store1"], ["Sams", "store2"], ["Johns", "store3"], ["Toms", "store4"]]
urls_list = ['store1.txt', 'store2.txt', 'store3.txt', 'store4.txt', 'store5.txt', 'store6.txt']
ls = []
for x in store_list:
    str_num = x[1]
    matching = [s for s in urls_list if str_num in s]
    x.insert(3, matching)
    ls.append(x)
for i in ls:
    print i
2
  • Both ettanany and rassar's answers work on my example, but they do not work for my actual script. When adding the [0] to the end of the matching line I get an IndexError: list index out of range. When adding the .pop() I get and IndexError: pop from empty list. Sigh, but when I run the code without either, it does as it should and returns a list in that element. Commented Dec 8, 2016 at 21:29
  • I understand now. Some of the lists are empty because they were generated improperly, therefore an empty list cannot be popped. Thanks again for the awesomeness. Commented Dec 8, 2016 at 21:35

2 Answers 2

1

Change the 6th line to:

matching = [s for s in urls_list if str_num in s][0]

The list comprehension automatically generates a list, so you need to take the first value of that list if you just want the string.

1
  • Wonderful rassar. Thank you. Commented Dec 8, 2016 at 21:16
0

matching is a list, you can use pop() to get your element like this:

x.insert(3, matching.pop())
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.