This forum is now read-only. Please use our new forums! Go to forums
Question on range(len(...)) (18/18)
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
results = []
for numbers in range(len(lists)):
for i in range(len(numbers)):
results.append(i)
return results
print flatten(n)
The code above doesn’t work; however, the code below works.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
results = []
for numbers in lists:
for i in numbers:
results.append(i)
return results
print flatten(n)
Based on what I learned in Code Academy so far, a loop such as
for i in x:
should be the same as
for i in range(len(x)):
So why isn’t the latter one working? Thanks!
Answer 5334ab25282ae33b69000947
for i in x:
Will step through x
and as it reaches each item it will store the value of it in i
for the duration of the loop.
eg. x = ["apple", "pear", "orange"]
i
will equal “apple” for the first loop, “pear” for the second etc.
for i in range(len(x)):
This will put a number value in i
up to the length of x
.
eg. x = ["apple", "pear", "orange"]
so len(x) = 3
i
will equal 1
for the first loop, 2
for the second etc.
The first loop will store a value in i
from x
, while in the second loop i
is just a counter
Hope this makes sense Good luck
Answer 533c010352f86352ba00243e
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists): results = [] for numbers in lists:
for item in numbers:
results.append(item)
print item
return results
print flatten(n)
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
1 comments
Sorry for the late reply. Thanks James!