Complex filtered list

Hi,

I’m trying to create a filtered list to show all products >= $10.

It’s based on this list:
items = [
(“Products1”, 10),
("Products2, 9),
(“Products3”, 13)
]

I created the list:
Filtered = [item for item in items if item[1] >=10]

What does the “item[1]” refer to and does it change as we iterate through the list?
I’m referring to the term “item[1]” right before the >=10 in the Filtered variable.

Thank you very much!

Josh

With loops and list comprehensions, you can always simplify it to clarify what’s what. It’s always good practice to know 100% of the variables you work with.

item_1_test = [item[1] for item in items]
print(item_1_test)

Also, don’t forget that formatting the code makes it easier to review (just press the </> button before you pasted the text). :sweat_smile:

1 Like

Great idea toastedpitabread!

This computer that I’m on doesn’t have python (it’s a chromebook:(
so I can’t test it right now.

In the above example what does the item[1] refer to and does it change as we iterate through the list?

Thank you again!

Respectfully,
Josh

You can run python online (albeit slowly) https://www.python.org/shell/.

The format some_list[x] can read as “access the value at x-index from some_list”. You’d have to review lists for more information on that. (It also works for strings but I don’t want to complicate it)

1 Like

Hi Toastedpitabread,

I admit, I don’t totally understand.
It sounds like “item1” is the index so it changes as it iterates through the list.
Can you please provide a simple example?

Thank you very much,
Josh

Lists in python can hold different types of objects (integers, strings, other objects, even lists). They are 0-indexed, so the first item in a list is always at index-0.

Some examples:

test_list = [1, 2, 3, 4]

print(test_list[0])
# prints: 1
print(test_list[1])
# prints: 2
print(test_list[2])
# prints: 3
print(test_list[3])
# prints: 4
print(test_list[4])
# IndexError: list index out of range

other_list = [5, 1, 3, 6]
print(other_list[0])
# prints: 5
print(other_list[1])
# prints: 1
print(other_list[2])
# prints: 3
print(other_list[3])
# prints: 6

It sounds like “item1” is the index so it changes as it iterates through the list.

@board4185331766 the thing being iterated is item, and not [1]. So it presupposes that the items are some sort of list or string.

test_list = ['bob', 'sam', 'wendy']

for i in test_list:
   print(i[1])

# 'o'
# 'a'
# 'e'

@board4185331766 sorry it wasn’t clear what you didn’t understand. Might’ve been too simple in the first example.

2 Likes

Hi Toastedpitabread,

This makes a lot more sense. Thank you very much!

Respectfully,
Josh

1 Like