Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
lHelp! Lists
#1
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?
Reply
#2
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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020