How can I iterate through a 2D list to just get the first index within each list?

Viewed 57
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]
 
# This outer loop will iterate over each list in the groups list
for group in groups:
  # This inner loop will go through each name in each list
  for name in group:
    print(name)`

Print out 'Jobs', 'Newton', 'Einstein'

2 Answers

This is where list comprehensions are really nice in Python:

groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]

print([group[0] for group in groups])

Result:

['Jobs', 'Newton', 'Einstein']

If you just want to do something with each individual first entry, you of course just do this:

for group in groups:
    print(group[0])

Or, without the indexing:

for (name, *__) in groups:
    print(name)

You can use list comprehension like this:

groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]
groups_only_first = [x[0] for x in groups]
print(groups_only_first)
Related