0

I wrote a code that takes a list and a starting point that, but if the starting point is not given I want it to start at 0. The problem I have is that I want it to iterate from the start (0) to the end (len(a_list)-1), however I don't know how to keep start going up by one each time until it has iterated through everything.

Here is a small crappy example:

def test(a_list, start = 0):
    final = []
    for i in a_list[start]:
        final.append(i)
    return final

print (test([[1,2,3,4],[2,3,4]]))

This outputs: [1, 2, 3, 4]

Whereas I want it to output [1, 2, 3, 4, 2, 3, 4]

without changing the print (test([[1,2,3,4],[2,3,4]])) and assuming the start point is not given how would i go about achieving this.

Thanks

user2101517
  • 700
  • 3
  • 11
  • 22

2 Answers2

2

There is no need to keep track of the indices of the items in your list. You simply iterate through the items themselves. However, in this case, you want to concatenate the lists using + rather than appending them together.

def test(list_of_lists):
    final = []
    for L in list_of_lists:
        final += L
    return final

If you need to start at a particular index, you can slice the list:

def test(list_of_lists, start = 0):
    final = []
    for L in list_of_lists[start:]:
        final += L
    return final

There are also several succinct ways to concatenate a list of lists like this including list comprehension, reduce, and itertools.chain.from_iterable.

print ([item for L in list_of_lists for item in L])
print (reduce(list.__add__, list_of_lists, []))

from itertools import chain
print (list(chain.from_iterable(list_of_lists))
Community
  • 1
  • 1
Stuart
  • 9,597
  • 1
  • 21
  • 30
0

Iterating with go through the entire list. You don't have to worry about it.

final = []
for i in a_list:
    final.append(i)

Or if you want to start from the start, do this:

final = []
for i in range(start, len(a_list - 1):
    final.append(i)

This will add values from the start to the end of the list.

Zizouz212
  • 4,908
  • 5
  • 42
  • 66