user2916886
user2916886

Reputation: 845

Python not all arguments converted during string formatting error while working with list of lists

I have list of list and I have this code in which I am accessing certain elements of the list and adding an increasing number to serve as an index. My sample list looks like this:

list1 = [['item1', '100', '07/05/2017'], ['item2', '115', '07/07/2017']....]

from this list I want to select first two element of the list and print like this(Note that I don't want to delete the last column from the list but just not print it):

1. ITEMS: item1, PRICE: 100 2. ITEMS: item2, PRICE: 115

I wrote this line of code to do that:

inner_list_str = ["%d. ITEMS: %s, PRICE: %s" % (i, *x) for i, x in enumerate(list1, 1)]

but I get error as: TypeError: not all arguments converted during string formatting. I think its because of 3 columns being in each element of my list but only 2 %s. How can I resolve it?

Upvotes: 0

Views: 59

Answers (3)

skrx
skrx

Reputation: 20488

Better use str.format or Python 3.6's format-strings. You can also unpack the sublist items to make the code more readable (if the sublists all have the same length).

inner_list_str = ["{}. ITEMS: {}, PRICE: {}".format(i, item, price)
                  for i, (item, price, _) in enumerate(list1, 1)]

Python 3.6+ only:

inner_list_str = [f"{i}. ITEMS: {item}, PRICE: {price}"
                  for i, (item, price, _) in enumerate(list1, 1)]

Upvotes: 2

itsmichaelwang
itsmichaelwang

Reputation: 2338

Enumerate will assign to the variable x your inner list, but you still need to specify which item(s) in the inner list you want in your comprehension. In your example, you are unpacking all three elements of your inner list with your star operator. Here's a runnable snippet of code that demonstrates what you want, only unpacking the first two variables:

list1 = [['item1', '100', '07/05/2017'], ['item2', '115', '07/07/2017']]
inner_list_str = ["%d. ITEMS: %s, PRICE: %s" % (i, x[0], x[1]) for i, x in enumerate(list1, 1)]

print inner_list_str

Personally, I prefer this over the star operator as it's more explicit, especially to people who have less familiarity with the ins and outs of Python.

Upvotes: 1

cs95
cs95

Reputation: 403030

You'll only want to select the first and second item. So this would work (python3.5):

>>> ["%d. ITEMS: %s, PRICE: %s" % (i, *(x[:-1])) for i, x in enumerate(list1, 1)]
['1. ITEMS: item1, PRICE: 100', '2. ITEMS: item2, PRICE: 115']

For older pythons, you'd instead have to use % (i, x[0], x[1]) because starred expressions outside assignment aren't supported.

Upvotes: 2

Related Questions