Day #22 - Introduction to Lists

Day #22 - Introduction to Lists

Β·

7 min read

Introduction

Welcome to my 22nd blog post. Today I learned about 'Lists' in python. I learned about indexing, accessing list items and list comprehension in python. Now let's dive deep into the details of list for a better understanding

So let's get started......

What is a 'List' in Python?

  • Lists are ordered collections of data items.

  • Lists help you to store multiple items in a single variable.

  • List items are separated by commas and enclosed within square brackets [].

  • Lists are changeable meaning we can alter them after creation i.e lists are mutable datatypes in python.

Example 1 -

lst1 = [1,2,2,3,5,4,6]
lst2 = ["Red", "Green", "Blue"]
print(lst1)
print(lst2)
[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']

Example 2 - Single list can contain items of different data types.

#list in python
marks = [3, 5, 6, "Harry", True, 6, 7 , 2, 32, 345, 23]
print(marks)
print(type(marks))
print(marks[0])
print(marks[1])
print(marks[2])
print(marks[3])
print(marks[4])
print(marks[5])
[3, 5, 6, 'Harry', True, 6, 7, 2, 32, 345, 23]
<class 'list'>
3
5
6
Harry
True
6

List Index

Each item/element in a list has its unique index. This index can be used to access any particular item from the list. Indexing in 'lists' just like 'strings' start from 0.

The first item has an index [0], the second item has an index [1], the third item has an index [2] and so on.

Example -

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
#          [0]      [1]     [2]      [3]      [4]

Accessing list items

We can access list items by using its index with the square bracket syntax []. For example colors[0] will give "Red", colors[1] will give "Green" and so on...

Positive Indexing:

As we have seen that list item have indexes, we can access items using these indexes.

Example :

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
#          [0]      [1]     [2]      [3]      [4]
print(colors[2])
print(colors[4])
print(colors[0])

Output -

Blue
Green
Red

Negative Indexing:

Similar to positive indexing, negative indexing is also used sometimes to access items in lists. The last item has an index [-1], the second last item has an index [-2], the third last item has an index [-3] and so on.

Example 1 -

marks = [3, 5, 6, "Harry", True, 6, 7 , 2, 32, 345, 23]
print(marks)
print(type(marks))

print(marks[-3]) # Negative index
print(marks[len(marks)-3]) # Positive index
print(marks[5-3]) # Positive index
print(marks[2]) # Positive index
[3, 5, 6, 'Harry', True, 6, 7, 2, 32, 345, 23]
<class 'list'>
32
32
6
6

Example 2 -

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
#          [-5]    [-4]    [-3]     [-2]      [-1]
print(colors[-1])
print(colors[-3])
print(colors[-5])
Green
Blue
Red

'in' Keyword

We can check if a given item is present in the list. This is done using the 'in' keyword.

Example 1 -

marks = [3, 5, 6, "Harry", True, 6, 7 , 2, 32, 345, 23]
print(marks)
print(type(marks))

if 6 in marks:   #this will print "Yes"
  print("Yes")
else:
  print("No")

if "6" in marks:   #this will print "No" , as here 6 is string
  print("Yes")
else:
  print("No")

Output -

[3, 5, 6, 'Harry', True, 6, 7, 2, 32, 345, 23]
<class 'list'>
Yes
No

Example 2 -

colors = ["Red", "Green", "Blue", "Yellow", "Green"]
if "Yellow" in colors:
    print("Yellow is present.")
else:
    print("Yellow is absent.")

if "Orange" in colors:
    print("Orange is present.")
else:
    print("Orange is absent.")

Output -

Yellow is present.
Orange is absent.

Range of Index

We can print a range of list items. This can be done by specifying 3 parameters viz

  1. Where do you want to start,

  2. Where do you want to end

  3. If you want to skip elements in between the range.

Syntax:

listName[start : end : jumpIndex]

Note: jump Index is optional. We will see this in later examples.

Example 1 -

marks = [3, 5, 6, "Harry", True, 6, 7 , 2, 32, 345, 23]
print(marks)
print(type(marks))

print(marks[0:7])
print(marks[1:9])
print(marks[1:9:3]) #here we use JUMP index, which skips to every 3rd element
[3, 5, 6, 'Harry', True, 6, 7, 2, 32, 345, 23]
<class 'list'>
[3, 5, 6, 'Harry', True, 6, 7]
[5, 6, 'Harry', True, 6, 7, 2, 32]
[5, True, 2]

Example 2 - printing elements within a particular range:

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[3:7])    #using positive indexes
print(animals[-7:-2])    #using negative indexes'

Explanation - Here, we provide an index of the element from where we want to start and the index of the element to which we want to print the values.

Note: The element of the end index provided will not be included.

Example 3 - printing all elements from a given index till the end

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[4:])    #using positive indexes
print(animals[-4:])    #using negative indexes

Example 4 - printing all elements from the start to a given index

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[:6])    #using positive indexes
print(animals[:-3])    #using negative indexes

Explanation - When no start index is provided, the interpreter prints all the values from start up to the end index provided.

Using 'jump' index

Example 1 - Printing alternate values

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[::2])        #using positive indexes
print(animals[-8:-1:2])    #using negative indexes

Output -

['cat', 'bat', 'pig', 'donkey', 'cow']
['dog', 'mouse', 'horse', 'goat']

Explanation - Here, we have not provided a start and index, which means all the values will be considered. But as we have provided a jump index of 2 to print only alternate values.

Example 2 - printing every 3rd consecutive value within a given range

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[1:8:3]) #here jump index is 3. It prints every 3rd element

Output -

['dog', 'pig', 'goat

List Comprehension

Used to create new lists from other iterables like lists, tuples, dictionaries, sets, and even in arrays and strings.

Syntax

List = [Expression(item) for an item in iterable if Condition]

  1. Expression: It is the item that is being iterated.

  2. Iterable: It can be lists, tuples, dictionaries, sets, and even in arrays and strings.

  3. Condition: This checks the condition to add the item to the new list or not.

Example 1 -

#list comprehension
lst = [i*i for i in range(10)]
print(lst)
lst = [i*i for i in range(10) if i%2==0]
print(lst)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 4, 16, 36, 64]

Example 2 - Accepts items with the small letter β€œo” in the new list

names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)
['Milo', 'Bruno', 'Rosa']

Example 3 - Accepts items that have more than 4 letters

names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if (len(item) > 4)]
print(namesWith_O)
['Sarah', 'Bruno', 'Anastasia']

Resources Used

You can watch the video of Day#22 by clicking on the below link πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

Conclusion

Thanks, guys for going through this blog post. On day #22 I solved a lot of problems using lists and wrote a bunch of code practicing various possibilities using different properties of list.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of python coding. This is it for Day #22

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


Β