0

I would like to loop through a list in python and usually I do in this way:

let's imagine a list into a variable called 'movie' where I want to print the even into a variable 'authors' and the odd into 'stars'. I would do like this:

stars = movies[0] #print the first
authors = movies[1] #print the second

for i in range(0, len(movies), 2):
    stars = movies[0+i]
    authors = movies[1+i]

But how can i do in this other way?

stars, authors = movies[0:2]

for i in range(0, len(movies), 2):
    stars #how can i insert "i"?

4 Answers 4

2

You can use slicing:

stars=movies[::2]
authors=movies[1::2]

stars consists of every other sample in the movies array, hence the step of 2. It starts with the 0th index, which was omitted above. You could also write stars=movies[0::2].

authors also uses a step of 2, but starts with the first index in movies.

You can check out the basics of indexing and slicing here.

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you don't need the value of movies afterwards you can use extended iterable unpacking

while movies:
    stars, authors, *movies = movies

Comments

0

Just use triple slicing (start:end:step):

stars, authors = movies[::2], movies[1::2]

Comments

0
for i in range(0, len(movies), 2):
    stars, authors = movies[i:i+2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.