Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to get first item in list on list in python3

I have a list in python like the following:

edge =  [[1, 2], [1, 3], [1, 4], [3, 4]]

I want to print 1 and 1 and 1 and 3; aka the first element of each sub-list.

I use this code:

for subList in edge:
    for firstItem in subList:
        print(firstItem)

But it prints all elements..

like image 338
Saeed Rahmani Avatar asked Sep 29 '15 08:09

Saeed Rahmani


People also ask

How do you access the first element of a list in python?

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.

How do I find the first element in a list?

Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

How do you print the first three elements of a list in python?

How do you print the first N numbers in a list Python? To get the first N elements of a list, use for loop with range(0, N), create a new empty list, and append the elements of source list to new list in the for loop. range(0, N) iterates from 0 to N-1, insteps of 1.


1 Answers

You are looping over all elements of all nested lists. If you only wanted to print the first element of each nested list, use indexing:

for sublist in edge:
    print(sublist[0])

If all nested lists have the same number of elements you could use unpacking:

for start, end in edge:
    print(start)
like image 107
Martijn Pieters Avatar answered Oct 04 '22 16:10

Martijn Pieters