List and List Comprehension in Python๐Ÿ

ยท

6 min read

List and List Comprehension in Python๐Ÿ

Hello everyone!! ๐Ÿ‘‹

I am Akshaya and this is my first blog post. I am currently learning Python, I want to share my progress and learnings. So.., HERE I AM! Wait no more.. Let's dive right into this post, List and List Comprehension - Know it all in under 6 minutes. started.gif

What is a Listโ“

List is one of the data structures in Python. They are used to store multiple items of different data types. That is, a list can have an integer, a floating-point number, a string or all three together in a single list. The items in a list are separated by commas and are enclosed in square brackets [ ].

Example:

my_list = ['red', 'blue', 1, 2, 0.5]

The list items are ordered, mutable and can contain duplicate values.

  • Ordered - Lists have a definite order.

  • Mutable - The list items can be changed ie., it can be removed, added or replaced with a new item.

  • Can contain duplicate values- same item can exist multiple times in a single list.

Example:

my_list = ['red', 'blue', 1, 2, 0.5, 1, 'red']

As you can see, the items 1 and red are repeated twice in the list and is acceptable.

Accessing the list items: The items in the list can be accessed using the index value.

๐Ÿ’ก Point to remember: Index value always starts from 0.

image.png

To access the item 'blue' from the list, pass it's index value. print(my_list[1])

Negative Indexing: Python supports negative indexing in lists. Negative indexing is used when the length of the list is unknown. It starts from the last item in the list as shown below,

image.png

To access the item 'blue' from the list using negative indexing, print(my_list[-6])

Know the List Methods:

List has several in-built methods. A method is a function that is associated with a particular object. Some of the list methods are,

append() - It is used to add an item to the end of the list.

my_list = ['red', 'blue', 1, 2, 0.5, 1, 'red']
my_list.append('black')
print(my_list)

Output:

['red', 'blue', 1, 2, 0.5, 1, 'red', 'black']


extend() - extends a list by appending all the items of another list.

my_list = ['red', 'blue', 1, 2, 0.5, 1, 'red', 'black']
my_list.extend([4, 5, 7])
print(my_list)

Output:

['red', 'blue', 1, 2, 0.5, 1, 'red', 'black', 4, 5, 7]


insert() - used to insert a new item in the specified index position.

my_list = ['red', 'blue', 1, 2, 0.5, 1, 'red', 'black', 4, 5, 7]
my_list.insert(2, 'yellow')     
print(my_list)

Output:

['red', 'blue', 'yellow', 1, 2, 0.5, 1, 'red', 'black', 4, 5, 7]

my_list1.insert(2, 'yellow') where -> 2 - is the index position at which the item 'yellow' is to be added.


remove() - removes a particular item from the list.

my_list = ['red', 'blue', 'yellow', 1, 2, 0.5, 1, 'red', 'black', 4, 5, 7]
my_list.remove(2)    
print(my_list)

Output:

['red', 'blue', 'yellow', 1, 0.5, 1, 'red', 'black', 4, 5, 7]

๐Ÿ’ก Note: ValueError will be raised, if the specified item does not exist in the list.


count() - returns the number of times an item appears on the list.

my_list = ['red', 'blue', 'yellow', 1, 0.5, 1, 'red', 'black', 4, 5, 7]
my_list.count(1)

Output: counts the number of times item 1 appeared in the list

2


index() - returns the index number of an item.

my_list = ['red', 'blue', 'yellow', 1, 0.5, 1, 'red', 'black', 4, 5, 7]
my_list.index('yellow')

Output:

2

๐Ÿ’ก Note: Remember, index always starts from 0 . 'yellow' is at index 2.


reverse() - reverses the items of a given list.

my_list = ['red', 'blue', 'yellow', 1, 0.5, 1, 'red', 'black', 4, 5, 7]
my_list.reverse()
print(my_list)

Output:

[7, 5, 4, 'black', 'red', 1, 0.5, 1, 'yellow', 'red', 'blue']


sort() - sorts the items of the list. It has two optional keyword arguments (key=None, reverse=False)

colors = ['red', 'yellow', 'blue', 'gray', 'white', 'black']
colors.sort()
print(colors)

Output:

['black', 'blue', 'gray', 'red', 'white', 'yellow']

The keyword argument 'reverse' is a boolean value. If specified as 'True', it will reverse the elements from higher order to lower.

colors = ['red', 'yellow', 'blue', 'gray', 'white', 'black']
colors.sort(reverse=True)
print(colors)

Output:

['yellow', 'white', 'red', 'gray', 'blue', 'black']


pop() - Removes the item from the list at the specified index and returns it. If no index value is specified, it removes and returns the last item in the list.

my_list = ['red', 'blue', 'yellow', 1, 0.5, 1, 'red', 'black', 4, 5, 7]
my_list.pop(4)
print(my_list)

Output:

0.5

['red', 'blue', 'yellow', 1, 1, 'red', 'black', 4, 5, 7]


copy() - returns a copy of a list.

my_list = ['red', 'blue', 'yellow', 1, 1, 'red', 'black', 4, 5, 7]
my_list.copy()

Output:

['red', 'blue', 'yellow', 1, 1, 'red', 'black', 4, 5, 7]


clear() - removes all the items in the list.

my_list.clear()
print(my_list)

The above code snippet returns an empty list [ ].


Now, lets talk about list comprehension.

LIST COMPREHENSION:

A simple way of creating a new list from an existing list.

Creating a New List (The normal method) :

We can create a new list from an existing list using FOR LOOP and then appending each item to the new list using append() method.

old_list = ['cat', 'rabbit', 'mouse', 'dog', 'horse']
new_list = []
for item in old_list:
    new_list.append(item)
print(new_list)

This would print ['cat', 'rabbit', 'mouse', 'dog', 'horse'] on the terminal.

However, instead of writing the above five lines of code, we can use a single line of code which does exactly the same function!!

easy.gif

Yes.! The list comprehension! - More efficient, readable and concise too. See the syntax below๐Ÿ‘‡ The if condition is optional.

new_list = [expression for item in iterable if condition]

Now, lets use the above mentioned example to create a new list using list comprehension.

old_list = ['cat', 'rabbit', 'mouse', 'dog', 'horse']
new_list = [animal for animal in old_list]
print(new_list)

image.png

Output:

['cat', 'rabbit', 'mouse', 'dog', 'horse']

Lets look at another example using if conditionals in list comprehension.

old_list = ['cat', 'rabbit', 'mouse', 'dog', 'horse', 'panda', 'elephant', 'donkey', 'tiger', 'horse']
new_list = [animal for animal in old_list if len(animal) >= 5]
print(new_list)

image.png Output:

['rabbit', 'mouse', 'horse', 'panda', 'elephant', 'donkey', 'tiger', 'horse']

In this example, we use the conditionals to check if the length of animal name is greater than or equal to five

if len(animal) >= 5

and we store only the animals which satisfies the condition.


Final Thoughts: โœจ

Kudos to you for making it this far ๐ŸŽ‰๐ŸŽ‰.

This sums up the list and list comprehension. List comprehension is widely used in Python and serves as a base for dictionary comprehension too. I hope you enjoyed this post. Now, all that's left for you is to - PRACTICE, PRACTICE, PRACTICE - look at the below code and comment down the answer ๐Ÿ˜œ

list1 = [1, 4, 2]
list2 = [4, 4, 'red']
new = [(x, y) for x in list1 for y in list2 if x != y]
print(new)

joke.gif

If you like the above content, a thumbs up ๐Ÿ‘ to this post and a follow on twitter @akshaya_lr would be appreciated. I am a learner, do share your valuable feedbacks/suggestions in the comments below. Have a great day, folks! See you soon with another post๐Ÿ™๐Ÿ’™

thank.gif

ย