
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to generate sequences in Python?
List comprehensions in python are useful for such tasks. These are very powerful expressions that you can use to generate sequences in a very concise and efficient manner. For example, if you want first 100 integers from 0, you can use −
Example
a = [i for i in range(100)] print(a)
Output
This will give the output −
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Example
Want the squares for first 10 even numbers? You can get it using −
a = [i * i for i in range(20) if i % 2 == 0] print(a)
Output
This will give the output −
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
These expressions can get much more powerful once you know how to use them.
- Related Articles
- How to process escape sequences in a string in Python?
- How to generate armstrong numbers in Python?
- How to generate XML using Python?
- How to generate a sorted list in Python?
- How to generate byte code file in python
- How to generate prime twins using Python?
- How to generate JSON output using Python?
- How to generate statistical graphs using Python?
- How to generate XML from Python dictionary?
- How to generate prime numbers using Python?
- How to generate non-repeating random numbers in Python?
- How to generate XML documents with namespaces in Python?
- Divide Array Into Increasing Sequences in Python
- How to generate a 24bit hash using Python?
- How to generate pyramid of numbers using Python?

Advertisements