1

I'm trying to convert a very basic statement, like this

for i in the_list:
    work.append(i)
    y = y[1:]

From a for loop, to a while loop. I use code like this a lot and have been trying to learn about different ways to write it, without a for loop.

3
  • 1
    While it would be fairly simple to do this, it wouldn't be a good use of a while loop. for looks much more appropriate. Commented May 7, 2015 at 3:27
  • 2
    This question was already answered here: stackoverflow.com/questions/18900624/… Commented May 7, 2015 at 3:27
  • @unicornication: were you able to resolve this? Commented Jun 6, 2015 at 18:54

2 Answers 2

3

One way to do this would be:

i, length = 0, len(the_list)
while i < length:
    work.append(i)
    y = y[1:]
    i += 1

Note: this is not recommended, the for loop would be considered more Pythonic - it is both shorter and more readable.

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

Comments

0

Well if the intention is to just remove the loop then, list comprehension is also a good option

work =[i for i in the_list]

1 Comment

List comprehension is also a loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.