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'
CodePudding user response:
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)
CodePudding user response:
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)
CodePudding user response:
You can also use the unpack operator to unpack the sublists and use zip to create an iterable of tuples. Since you want the first elements in each list, you want the first element of the zip object. You can't index a zip object so you cast it to tuple and take the first element.
x = tuple(zip(*[["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]))[0]
print(x)
Output:
('Jobs', 'Newton', 'Einstein')
