-4

I want to create the list [0, 2, 3, ..., 234] in python, possibly within a row and without listing all numbers explicitly

I know that following code works:

list1 = [0]
for i in range(2,235):
    list1.append(i)

But are there any possibilities to finish that within a row?

1
  • 3
    You can literally write [0, 2, 3, ..., 234], that's valid Python :-) Commented Sep 10, 2024 at 0:10

3 Answers 3

4

Another efficient way, combining simplicity and performance, is to use unpacking:

list1 = [0, *range(2, 235)]
Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest that this be accepted as the correct answer rather than mine (though I agree with @nocomment about overloading the keyword), since it's not only a one-liner per the OP but empirically performs better than mine.
2
list1 = [0] + list(range(2,235))

list will expand a lazy enumerator.

Comments

0

This is probably not as efficient as the other two answers but is a direct translation of your code to a 1 liner.

list1 = [0] + [i for i in range(2,235)]

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.