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..
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.
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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With