Does age need to be at the beginning or end of all_ages?

Pint for clarification:
It isn’t clear in #4 from the words “Create a new list called all_ages that combines age with the following list:” means
age + [numbers]
and not [numbers] + age.
This apparently makes a difference as to where age is inserted.

all_ages = age + [32, 41, 29] #age goes to beginning
#all_ages = [32, 41, 29] + age #age goes to the end
print(age)
print(all_ages)

This is important since if we print the zipped list items,

for x in name_and_age:
  print (x)

we want this…

('Ainsley', 42)
('Ben', 32)
('Chani', 41)
('Depak', 29)
2 Likes

But it says "the ages for Ainsley, Ben, and Chani:

[32, 41, 29]"

So it should be all_ages = [32, 41, 29] + age, right?

3 Likes

When we zip two lists of equal length, we get a zip object of the same length comprised of name, age pairs as tuples. This is not a list unless we cast it to one, and printing will consume the object. I’m not sure that we can extend a zip object (rather doubtful given the nature of iterators) so we have to go back to the original lists and extend them.

names = ['Ainsley', 'Ben', 'Chani']
ages = [32, 41, 29]

We can extend them with append() or by concatenating a list as follows,

names += ['Dupak']
ages += [29]

Or we can extend a list cast from a zip object. First, cast the list…

names_and_ages = list(names_and_ages)

That will consume the zip object but we have its tuples. Now we can append or concatenate another tuple, as suits…

names_and_ages += ('Dupak', 29)

which will give us,

[('Ainsley', 32), ('Ben', 41), ('Chani', 29), ('Dupak', 29)]

Bottom line, if we wish to continue using the data structure created with zip(), then it must be cast to a list, first.

2 Likes

apart from zipping i think we have a misunderstanding with the text. it says dupak’s age is 42, at first. in order to make the list right I made [xxxx] + age

3 Likes

Looks, to me, like you are correct. Depak’s age is 42, not 29.

1 Like

I’m having a similar problem. Is there a typo somewhere in the task? Because we should need to write all_ages = [[32, 41, 29] + age], right? That way, Depak’s age will be correctly associated with 42, since he is the 4th name on the list. When I wrote that as my answer, the software said my answer was wrong. But I wasn’t sure if it’s wrong because of the typo or because of my syntax. I did some trial and error using “print” to determine that I don’t need that extra set of brackets and that it’s enough to write all_ages = [32, 41, 29] + age.

2 Likes

Where is the bug? Everything looks fine, or at least in working order.

the instruction says " Depak’s age is 42 . Use .append() to add 42 to age ." That means “Age” comes after the list so it can be attached to “Depak” because of where its on the list. That’s what I did and it works for me.

[(‘Ainsley’, 32), (‘Ben’, 41), (‘Chani’, 29), (‘Depak’, 42)]