2

What happens in the case of a following for loop in python? How will the values of i change in each iteration. Does the sequences x and y combine to form a single sequence?

for i in x, y:
    do_something(i)

The code on which I'm trying is like this:

for sentence in snippet, phrase:
    result = sentence[:]

snippet and phrases are parameters whose values will be replaced by list, i.e., snippet and phrase both will be lists.

0

1 Answer 1

2

UPDATE: Okay, turns out you're asking about something entirely different.

The code you have will not combine snippet and phrase. On the first iteration of the loop, a copy of snippet will be assigned to result. On the second iteration, a copy of phrase will be assigned to result, replacing the old value. If you want to create a list with the elements of both snippet and phrase, you can just use

result = snippet + phrase

or if you really want to use a loop,

result = []
for sentence in snippet, phrase:
    result += sentence

x, y is a tuple. In other words, it's parsed like this:

for i in (x, y):
    do_something(i)

That means do_something will be called once on x, and once on y.

If you want to iterate over pairs of corresponding elements from x and y, use zip:

for i in zip(x, y):
# or
# for x_element, y_element in zip(x, y):
    do_something(i):

If you want to iterate over the elements of x, then the elements of y, you can use

import itertools
for i in itertools.chain(x, y):
    do_something(i)

or if x and y are both lists or both tuples,

for i in x + y:
    do_something(i)
Sign up to request clarification or add additional context in comments.

1 Comment

@kartikey_kant: See expanded answer.

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.