loading...

List Comprehension

idimaimuna profile image M__ ・2 min read

Hi there, I am back with another python concept; list comprehension.

A list is a collection of related data e.g. a collection of my favorite movies or books. Lists in python can contain numbers, strings, lists etc. In python you can create lists like so:

my_movies  = ['Gone Girl’, ‘The Current War’, ‘Crazy Rich Asians']

#if you are creating a list of a number of elements from input given
my_movies = [] #declare an empty list
for movie in range (3): #loop through 3 elements
    movie = input () #accept input from the user
    my_movies.append(movie ) #add that input to your list

print(my_movies) #display your complete list

A list comprehension is a simple way of creating lists in one line instead of writing many lines of code. One thing I noticed is when using list comprehensions most of the time ranges are involved:

#loops through numbers starting from 1 and stopping at 11(not inclusive)
first_ten_numbers = [n for n in range (1,11)]
print(first_ten_numbers)

'''
Output:
[1,2,3,4,5,6,7,8,9,10]
'''

One can also use ‘if- statements’ in list comprehensions to check a certain condition:

#loops through numbers starting from 1 and stopping at 11(not inclusive) and display only even numbers
first_ten_even_numbers = [n for n in range (1,11) if n%2 == 0]
print(first_ten_even_numbers)
'''
Output:
[2,4,6,8,10]
'''

It is also possible to make nested lists:

#loops through numbers starting from 1 and stopping at 4(not inclusive) 
multi_list = [[x, y] for x in range (1,4) for y in range (1,4)]
print(multi_list)
'''
Output:
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]] 
'''

List comprehensions can be very helpful when you need to create simple lists and it saves you a couple lines of code so it’s worth noting.

Posted on by:

idimaimuna profile

M__

@idimaimuna

New programmer interested in web development and python as well. Aspiring to learn and be better than I started.

Discussion

markdown guide