-2

A basic program that intends to generate a new list containing the elements of list2. Followed by the elements of list1 in reverse order I can't seem to understand what the commented line means.

 def combine_lists(list1, list2):
      new_list = list2
      for i in reversed(range(len(list1))):   #this one
        new_list.append(list1[i])
      return new_list
    
    Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
    Drews_list = ["Mike", "Carol", "Greg", "Marcia"]
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Levi
  • 33
  • 7
  • 1
    `reversed(range(len(list1)))` is a horrible way to write python code. Print the values of `i` inside the loop and you'll understand what it does. Use the same code without `reversed` and print the same. – Diptangsu Goswami Jul 12 '20 at 11:03
  • To debug and understand a code, print the values and you'll get it – azro Jul 12 '20 at 11:05
  • `len()` returns the length of the list. `range()` returns a list with the argument as the max. `reversed()` returns a reverse iterator of this list, yes, you guessed it, in reverse order. – Parth Shah Jul 12 '20 at 11:05
  • If `n = len(list1)`, i iterates through the numbers `[(n-1), (n-2), ...0]`. This is since reversed just iterates in the reverse direction i.e. range(n) would be `[0, ... n-1]`. – DarrylG Jul 12 '20 at 11:06

2 Answers2

1

I changed the comments to make them readable:

def combie_lists(list1, list2):
      new_list = list2  #define a new list with the elements of list 2
      for i in reversed(range(len(list1))): #takes the numbers 0,1,2,3,... to len(list1) in reverse
        new_list.append(list1[i]) #add the element in list1 with the corresponding index
      return new_list #return the new list

BTW you can do it like that:

combie_lists= lambda l1, l2: l2 + l1[::-1]
pgp1
  • 103
  • 1
  • 13
1

Breakdown of the line:

for i in reversed(range(len(list1)))

Suppose that list1 = [1, 2, 3].

Then len(list1) = 3 and the range will generate numbers from 0 to 2.

reversed flips the order, into the numbers 2, 1, 0, and to print them from the range_iterator object, you need to iterate over it which is what the for-loop does:

for i in reversed(range(len(list1))):
    print(i)

Results in:

2
1
0
Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53