

While the first range will hold the list of multipliers corresponding to different rows, on the other hand, the second range will hold the result values. Further, we’ll need two ranges in our loop. 10.Let’s advance our understanding of looping with multiple variables by applying concepts of ranges and the zip operator to generate multiplication tables, where each row shows up in the format: factor x multiplier = resultĪs the factor will remain the same in all the rows, we’ll have to loop through two multiplier and result variables. We can use sortWith() and sortedWith() for sorting of lists using a Comparator object as an argument.įor a more in-depth look into sort operations while working with lists in Kotlin, refer to our Guide to Sorting in Kotlin article. If we want to return a list after sorting, we can use the sortedBy() and sortedByDescending() methods. The collection must be a mutable list since methods will use the natural order of the elements and will sort in-place. We can use sortBy() and sortByDescending() methods to sort lists based on specific properties of a given object. Val sortedCountriesDescending = countries.sortedDescending() If we want to return a list after sorting, we can use sorted() and sortedDescending() methods: val sortedCountriesAscending = countries.sorted() So, the collection must be a mutable list. These methods will use the natural order of the elements and will sort in-place. Val sortCitiesDescending = cities.sortDescending() We can use sort() and sortDescending() methods to sort lists in Kotlin in ascending and descending order, respectively: val sortCitiesAscending = cities.sort() Let’s take a look at how the slice() method works: val sliceListUsingIndices = countries.slice(1.4)ĪssertEquals(4, sliceListUsingIndices.size) val sliceListUsingCollection = countries.slice(listOf(1, 4))ĪssertEquals(2, sliceListUsingCollection.size) 7. Unlike subList(), this method will create a new list with the subset of elements. We can use the slice() method to retrieve part of the list based on indices. Moreover, the Collection interface provides another method to retrieve parts of the list. Let’s have a look at an example to create a sublist: val subList = countries.subList(1, 4) So, any structural changes in the original list make the behavior of the view undefined. Python Program list1 4, 52, 6, 9, 21 index 0 while index < len(list1) : print(list1 index) index + 1 Output 4 52 6 9 21 2. The subList() method returns a view of the original list and will change with it. Iterate Python List using While Loop In this example, we will take a Python List, and iterate over all the elements of this list using while loop. The parameters for the method are used to define a specified range of the list between the fromIndex (inclusive) and toIndex (exclusive).


We can use the subList() method to retrieve a part of the list.
