Hi guys, I’m trying to use only Method 2 in solving this problem. I read through various threads but cannot seem to find the definitive answer. Here’s my code, I think the error lies somewhere in append section, but cannot figure it out.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for number in range(len(lists)):
for i in range(len(number)):
results.append(i)
return results
print flatten(n)
It does, there is a valuable lesson to be learned here.
One of coding efficient.
In this case, there is the opportunity to only use one for loop instead of two. This is much easier, clearer and even a (very little) bit more efficient.
In short: you should always try to look for the easiest or most efficient way when programming.
And you decided to pull my chain rather than provide a response of your own? If the learner doesn’t post a link are we supposed waste our time tracking down the lesson? Where is this ‘method 2’ the OP (and now you) refers to?
This topic was started and replied to 5 days ago, and abandoned by the OP. Can I take that to mean they found a clue to the answer in my post (concatenation of lists)?
Still don’t know which exercise this is. Why is everyone looking at me, rather than just answering the OP? It’s bad enough the OP doesn’t appear to be watching this topic. We are just spinning our wheels here.
Create a function called flatten that takes a single list and concatenates all the sublists that are part of it into a single list.
On line 3, define a function called flatten with one argument called lists.
Make a new, empty list called results.
Iterate through lists. Call the looping variable numbers.
Iterate through numbers.
For each number, .append() it to results.
Finally, return results from your function.
It should be fair to iterate the outer object without using a range…
def flatten(lists):
results = []
for numbers in lists:
for x in range(len(numbers)):
results.append(numbers[x])
return results
print flatten(n)