0

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?

1
  • 2
    Try using .format() instead. It's cleaner. (Also, your hunch is correct: only two %s's.) Commented Jul 20, 2017 at 9:35

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)]

Comments

1

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.

Comments

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.