Python Forum
lHelp! Lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: lHelp! Lists (/thread-25808.html)



lHelp! Lists - bwdu - Apr-12-2020

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?


RE: lHelp! Lists - buran - Apr-12-2020

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)