The list is the most versatile python data structure and stores an ordered sequence of elements, just like the to-do-list.In Python, Lists are mutable, meaning that the details can be altered, unlike tuples or even strings. These elements of a list are called items and can be any data type.
Now for understanding this article, we need to understand the range() function.
my_list = list(range(0,10,2)) #my_list becomes [0, 2, 4, 6, 8]
So, the range() function creates a sequence of numbers. First parameter of range() function is the starting number, the second parameter is number to stop before it and the third parameter is steps between these numbers(By default it is 1).
Now, we are going to look at some awesome tricks we can do on the lists in python ...
So, let's create a list first.
my_list = list(range(1,10,2)) #creates my_list with the values of [1, 3, 5, 7, 9]
print(my_list[2]) #prints the value at given index i.e. 5
Now, we know that we can get the desired value by index. Here comes the cool part, we can give a range in the [] brackets And get the values within that range. For example-
print(my_list[0:4]) #Prints [1, 3, 5, 7]
The first parameter 0 means the starting point. The second parameter means how many numbers you want to get. We can give the 3rd parameter to get the interval also.
Now, coming back to list comprehension in python. First, let me tell you the problem list comprehension is trying to solve.
Suppose we have given a list of string.
names = ["react", "angular", "ember"]
and we need to use upper case on every string
upper_case_names = []
for name in names:
upper_case_word = name.upper()
upper_case_names.append(upper_case_word) #["REACT","ANGULAR","EMBER"]
What if we could do the above code in one line only! So, here comes the list comprehension.
upper_case_names = [name.upper() for name in names] #["REACT","ANGULAR","EMBER"]
And Done!
Explanation: We start with the empty list []. Then on the right-hand side, we put the iterator or conditional, and on the left side, we put statements that we need to execute. That's it.
You can do so many cool stuff with the list comprehension.
And that's it for this article.
Top comments (0)