Python – Get the last element of a list

In Python, we can use index -1 to get the last element of a list. #!/usr/bin/python nums = [1, 2, 3, 4, 5] print(nums[-1]) print(nums[-2]) print(nums[-3]) print(nums[-4]) print(nums[-5]) print(nums[0]) print(nums[1]) print(nums[2]) print(nums[3]) print(nums[4]) Output 5 4 3 2 1 1 2 3 4 5 Yet another example. #!/usr/bin/python # getting list of nums from the …

Read more

Java – Get the last element of a list

In Java, index starts at 0, we can get the last index of a list via this formula: list.size() – 1 JavaExample1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); System.out.println(list.get(list.size() – 1)); System.out.println(list.get(list.size() – 2)); System.out.println(list.get(list.size() – 3)); …

Read more