0

Most of my scripting experience comes from bash and perl. This question is useful from someone transitioning from these languages to python. The other questions in the stackoverflow suggestions column concerning flattening two lists in python are too 'pythonic'.

This is from page 14 in the headfirst python book. They want you to combine two lists in a roundrobin fashion. This script results in :

 ['The Holy Grail', 1975, 'The Life of Brian', 1979]

I don't know if I am having trouble popping the value from the list or appending it to the new list.

movies = ['The Holy Grail', 'The Life of Brian', 'The Meaning of Life'] 
years = [1975,1979,1983]
combi = []

for i in movies: 
    popmov = movies.pop(0)
    popyea = years.pop(0)
    combi.append(popmov)
    combi.append(popyea)

print(combi)
capser
  • 2,442
  • 5
  • 42
  • 74

2 Answers2

1

You never remove elements from a list (here movies) while iterating on it

Here use the indexes

for i in range(len(movies)):
    combi.append(movies[i])
    combi.append(years[i])

Or better the method zip that pairs the given lists:

for movie, year in zip(movies, years):
    combi.append(movie)
    combi.append(year)

# or shorter
for pair in zip(movies, years):
    combi.extend(pair)
azro
  • 53,056
  • 7
  • 34
  • 70
0

You shouldn't iterate over a list and remove items at the same time.

This works:

movies = ['The Holy Grail', 'The Life of Brian', 'The Meaning of Life'] 
years = [1975,1979,1983]
combi = []

for _ in range(len(movies)):  # this runs loop the number of times the length of first list
    popmov = movies.pop(0)
    popyea = years.pop(0)
    combi.append(popmov)
    combi.append(popyea)

print(combi)