Python Forum
Using range over slicing when looping through lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using range over slicing when looping through lists
#1
Hi Folks! Beginner question. Which one of these two are less processor costly?
my_list = [2, 3, 11, 5, 1, 9, 7, 15, 13]
largest = my_list[0]

for i in range(1, len(my_list)):
    if my_list[i] > largest:
        largest = my_list[i]

print(largest)
Or

my_list = [2, 3, 11, 5, 1, 9, 7, 15, 13]
largest = my_list[0]

for i in my_list[1:]:
    if i > largest:
        largest = i

print(largest)
Or not much of a difference, except that latter looks more elegant ?
Thank you!
Reply


Messages In This Thread
Using range over slicing when looping through lists - by GJG - Jan-04-2021, 09:36 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020