How do I display all of one value from a nested list?

Viewed 614

If I have a nested list like this (the actual data will be a random length):

data = [['a', 'b', 'c', 'd'],['1', '2'],['3','4']]

How would I display only the first item in each list (a, 1, 3) using a loop.

for i in range(len(data)):
    print() #what goes here?
3 Answers
for i in range(len(data)):
    print(data[i][0]) 

or

for i in data:
    print(i[0])

This code will display the first value of nested list at index i. But I'm confused if those data will be stored in another list or tuple.

There are several ways.

To continue using an index like you currently are:

for i in range(len(data)):
    print(data[i][0])

In this method we get each nested array by accessing data[i] then access the first element of the nested array by accessing data[i][0].

However using an index to iterate through a list is not considered very pythonic; a more common way would be as follows:

for nestedArr in data:
    print(nestedArr[0])

By using in in this way each nested array is assigned to nestedArr, then we can access the first element of that nested array the same way as above.

Note:
Be careful to make sure that each element in data is actually a list and that each nested list has at least 1 element. You may wish to use an if statement and the len function to verify this before attempting to print the first element.

Shortest method is list comprehension:

print([e[0] for e in data])
Related