0

I have a list of lists containing information about smartphone applications. Each list (within the list) contains the same type of information, in the same order. [id, name, ..., ].

The list of lists looks like this: [[id1, name1,...], [id2, name2, ...]]

I want to access the 10th index in each list and check its value.

I tried this, but it does not work. I imagined this would iterate over every list, except the first which is a header, and would select the 10th item in each list.

for c_rating in apps_data[1:][10]:
    print(c_rating)

Instead, it prints out every item within the 10th list.

The given solution is:

for row in apps_data[1:]:
    c_rating = row[10]
    print(c_rating)

I understand why this code works. It breaks the process into two steps. I don't understand why the first code does not work. Any help would be appreciated.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Jonny G
  • 1
  • 2
  • Your iterable object is `apps_data[1:][10]`. This means the `for` loop is iterating over the 10th item in `apps_data[1:]`. – berkelem Apr 03 '19 at 12:04
  • That's what I though @berkelem, but that's not what it prints out. It prints out [id10, name10, ...]. So, it prints the 10th list, not the 10th item in all lists. Do you know how this could be done in one line, or must it be broken into 2 lines like in the solution? – Jonny G Apr 03 '19 at 12:13
  • That's what I said. The 10th item in your iterable is the 10th list. If you want you can remove one line by writing `for row in apps_data[1:]: print(row[10])` – berkelem Apr 03 '19 at 12:16
  • Possible duplicate of [Extract first item of each sublist in python](https://stackoverflow.com/questions/25050311/extract-first-item-of-each-sublist-in-python) – Georgy Apr 03 '19 at 12:49

1 Answers1

1

That's due to the python expression evaluation order. apps_data[1:][10] is evaluated in this order:

  • apps_data[1:] -> this gives a list of the inner lists with all but the first inner list. Let's call this inner_lists

  • inner_lists[10] -> this gives you the 10th element from that list of lists. Which gives you one of those inner lists.

So you end up with a select + select

What you want is a iterate + select. You can do it like this:

[print(x[10]) for x in apps_data]

This goes through all the inner_lists, selecting the 10th element from each and prints it.

rdas
  • 20,604
  • 6
  • 33
  • 46