For this exercise, how can I edit the existing list variable in the code to add new data items?
Answer
A list is an ordered collection of items. Lists are enclosed using the square brackets [] and each item is separated in the list using a comma. To edit an existing list, go the inside of the closing bracket ] and type a comma and then the new item to add to the list. To add multiple items, repeat the process by adding another comma and a new item but do not go beyond the closing square bracket of the list.
my_list = [1, 2, 3, 4]
# Edit the list in place. The new list will look like this:
my_list = [ 1, 2, 3, 4, 5]
I really went the long way round on this one. I figured writing it out that way would be cheating. I couldn’t remember Codecademy teaching me how to add something to a list. I tried ‘+=’ addition assignment; of course that didn’t work. Finally I went to w3schools and got the following solution:
One could also use the += operator to add new list items.
heights = [61, 70, 67, 64, 65]
heights += [78]
print (heights)
This will print [61, 70, 67, 64, 65, 78]
append() was specifically designed to add an item to the list, list extending also has it usage. So you need to know both, so you can the right approach for the problem you are facing
Hey, quick question regarding this exercise. Assuming I was I was working with a long list of elements, say, 1000 instead of just 4 in broken_heights. Manually separating the elements in the list with commas would be laborious. Would it be possible to use a for loop to accomplish this?
What determines that values are broken heights? Sure, we could write loop + logic to automate this task, but then you would need some kind of requirement.
Can you please also provide me the exercise url/link? I really need to see the instructions
A list needs to have certain syntax, you can’t just violate syntax, that results in a syntax error.
you could make the broken heights into a string:
broken_heights = "65 71 59 62"
that would work.
But what determines that a height is broken? We can write code to generate broken heights, but then there needs to be a reason for heights to be broken.
# Add a single item to the end
my_list.append(5) # faster, but in-place
my_list.add(5)
my_list = my_list + [5] # concatenate: slower
# Add many items at the end
my_list.extend([5,6,7]) # faster, but in-place