Skip to main content

Further into the lists..

So, let's continue our learnings about the lists in python!
     Why and how  to use list comprehension?
List is one of the most useful collection data type in python.It is a collection which is ordered and changeable.It Allows duplicate members.
  Many of us would have thought of what if we want to manipulate each and every  list element?
Suppose you are given a list of numbers and you want to add 1 to each element in your list:
my_list = [1, 3, 3, 7]
my_list_plus_one = my_list + 1 
and if you have thought of some code like above then its not gonna  work.
You would get this error:
 TypeError: can only concatenate list (not "int") to list. 
Python thinks that you want to add a list and an integer together, which doesn’t make any sense.
So how do we manipulate the list?
The answer is using list comprehension syntax.
Example:

my_list_plus_one = [num + 1 for num in my_list]
print(my_list_plus_one) 
# Output: [2, 4, 4, 8]
Essentially, you can iterate through my_list  using a condensed for-loop syntax. 
You can also add if and if-else statements like this:
Example 1:
filtered_out_low_nums = [num + 1 for num in my_list if num >= 5]
print(filtered_out_low_nums) 
  Output: [8]

Example 2:
all_high_nums = [num + 1 if num >= 5 else 5 for num in my_list]
print(all_high_nums)
  

   Output: [5, 5, 5, 8]

So  this is how we can easily perform various operations on list.
Learn more about LIST COMPREHENSION in python :here
 
see you all in the next article!
              -Shreya Uttarwar (L-69)

Comments

  1. Example helps to understand concepts better.Thanks for this amazing explanation!!

    ReplyDelete
  2. Amazing content..!! Keep up good work..

    ReplyDelete
  3. Thanks for the explanation. This Will Help students in understanding the concept of lists better.
    Keep up the good work!!

    ReplyDelete
  4. Nice and easy explanation! Keep it up.

    ReplyDelete

Post a Comment