Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Edited on

     

Python List Comprehension

List Creation

The below code is the normal way of creating a list in python and using the append function to append an element at the end of the list.

Python List

num_list = []num_list2 = ['Hello', 'world']num_list.append(1)num_list.append(2)num_list.append(3)num_list.append(4)num_list.append(5)print(num_list)print(num_list2)Output:[1, 2, 3, 4, 5]['Hello', 'world']
Enter fullscreen modeExit fullscreen mode

List Creation Using The List() Function
The list() function doesn’t take any argument and constructor creates an empty list and returns it. The list is then appended using the append function.

Python List using list() function

num_list = list()num_list.append(1)num_list.append(2)num_list.append(3)num_list.append(4)num_list.append(5)print(num_list)Output:[1, 2, 3, 4, 5]
Enter fullscreen modeExit fullscreen mode

Python List Comprehension

In the above section, we took a brief look at the python list, now we will understand what is list comprehension in python.

In the above examples, we either first created an empty list or manually added the items. List Comprehension makes it easy for us.

Example:

[expression for an item in iterable]
Enter fullscreen modeExit fullscreen mode
num_list = [number for number in range(1, 10)]print(num_list)Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen modeExit fullscreen mode

This would have taken 8-9 lines to add elements to a list or we would have used a loop that would have taken about 2 lines of code too. But Comprehension List can do that in only a single line.

Python List using loop

list_num = []for num in range(0,10):    list_num.append(num)print(list_num)
Enter fullscreen modeExit fullscreen mode

Comparing this example with the list comprehension, there the loop is directly placed in the square brackets and an expression sits before the loop that is basically what is stored in the list.

Example:

Change in Expressionnum_list = [number**2 for number in range(1, 10)]print(num_list)Output:[1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen modeExit fullscreen mode

number**2 – This expression makes a list of squares of numbers between 1 to 10 (excluding 10).

Read the whole postPython List Comprehension from the original Post.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Developer | Blogger
  • Joined

More fromDivyanshu Shekhar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp