Python Forum

Full Version: lHelp! Lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
a = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

lastelements = []
for i in range(len(a)):
    for t in a[i]:
        lastelements.append(t[1])

print(lastelements)

  
Guys, how can i fix this, TypeError: 'int' object is not subscriptable, for line 6?
for t in a[i]:
Here you iterate over elements of each tuple, which are integers. So, trying t[1] raise an error
Note also that indexes start from 0, so range(len(a)) would produce error, it should be len(a)-1 which is max index.

How to do it:
my_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
last_elements = []
for item in my_list: # pythonic way to iterate over elements of a lists
    last_elements.append(item[-1]) # python allows for negative indexes
 
print(last_elements)
or with list comprehension
my_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
last_elements = [item[-1] for item in my_lyst]
print(last_elements)