Lists and List Methods in Python. Topic-17

Lists and List Methods In Python

Python Lists:

The list is an ordered collection. In the list, we can store the multiple elements. A list can hold multiple data items in a single variable. Items in a list are separated by commas and enclosed within square brackets []. Lists are mutable, meaning you can alter them after creation. Let’s see an example:

list1 = [1, 2, 2, 3, 5, 4, 6]
list2 = ["Red", "Green", "Blue"]
print(list1)
print(list2)

The Output Of This Code Will Be:

Output
[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']

List Indexing:

List Index:

Every element that is present in the list, they all have a unique index number. Using the index number we can access specific elements in the list. The first item has an index [0], the second item has an index [1], the third item has an index [2], and so on.

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

We can access list items using their index with square bracket syntax []. For example, colors[0] will give us “Red”, colors[1] will give us “Green”, and so forth.

Positive Indexing:

As we’ve seen, list items have an index number, we can access these items through the index number. Let’s see an example.

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

print(colors[2])
print(colors[4])
print(colors[0])

The Output Of This Code Will Be:

Output
Blue
Green
Red  

Negative Indexing:

Similar to positive indexing, also negative indexing is used to access items but from the end of list. The last item has an index of [-1], the second-last item has an index of [-2], and so on. Let’s see an example for a better understanding.

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

print(colors[-1])
print(colors[-3])
print(colors[-5])

The Output Of This Code Will Be:

Output
Green
Blue
Red 

Check Whether an Item is Present in the List:

We can check if a specific item is present in the list using the ‘in’ keyword. Let’s see an example:

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

The Output Of This Code Will Be:

Output
Yellow is present.

Range Of Index:

We can specify the range of the list and print the elements, where you want to start, where you want to end, and if you want to skip elements in between the range. Let’s see an example:

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

The Output Of This Code Will Be:

Output
['mouse', 'pig', 'horse', 'donkey']
['bat', 'mouse', 'pig', 'horse', 'donkey']

List Comprehension:

  • List comprehensions are used to create a new list from other iterables such as lists, tuples, dictionaries, sets, arrays, and even strings.
  • Using list comprehensions we can filter items based on specific conditions.

Syntax:

Syntax
NewList = [Expression(item) for item in iterable if Condition]
Python
  • Expression: It represents the item being iterated.
  • Iterable: It can be a list, tuple, dictionary, set, array, or string.
  • Condition: It checks whether the item should be added to the new list or not.

Example 1:

names = ["Shivam", "Priti", "Yashika", "Harsh", "Sarthak"]
names_with_a = [item for item in names if "a" in item]
print(names_with_a)

The Output Of This Code Will Be:

Output
['Shivam', 'Yashika', 'Harsh', 'Sarthak']

Here, items are selected from the ‘names’ list that contains the letter “o,” and a new list (names_with_O) is created from those selected items.

Example 2:

names = ["Shivam", "Priti", "Yashika", "Ram", "Das"]
long_names = [item for item in names if len(item) > 4]
print(long_names)

The Output Of This Code Will Be:

Output
['Shivam', 'Priti', 'Yashika']

Here, items are selected from the ‘names’ list that have more than four characters, and and a new list (long_names) and store the long name in the ‘long_name‘ variables.

If you don’t know the “For & While Loops in Python” just click on read more.

List Methods or operation:

1. `sort()` Method:

Ascending order:

colors = ["voilet", "indigo", "blue", "green"]
     colors.sort()
     print(colors)
     
     num = [4, 2, 5, 3, 6, 1, 2, 1, 2, 8, 9, 7]
     num.sort()
     print(num)
Python

The Output Of This Code Will Be:

Output
['blue', 'green', 'indigo', 'voilet']
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
Python

Descending Order:

colors = ["voilet", "indigo", "blue", "green"]
colors.sort(reverse=True)
print(colors)
num = [4, 2, 5, 3, 6, 1, 2, 1, 2, 8, 9, 7]
num.sort(reverse=True)
print(num)
Python

The Output Of This Code Will Be:

Output
['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]
Python

2. `reverse()` Method:

   Reverses the order of the list.

colors = ["voilet", "indigo", "blue", "green"]
colors.reverse()
print(colors)
     
num = [4, 2, 5, 3, 6, 1, 2, 1, 2, 8, 9, 7]
num.reverse()
print(num)
Python

The Output Of This Code Will Be:

Output
['green', 'blue', 'indigo', 'voilet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]
Python

3. `index()` Method:

Returns the index of the first occurrence of the list item.

colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.index("green"))

num = [4, 2, 5, 3, 6, 1, 2, 1, 3, 2, 8, 9, 7]
print(num.index(3))
Python

The Output Of This Code Will Be:

Output
1
3
Python

4. `count()` Method:

Returns the count of the number of items with the given value.

colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.count("green"))

num = [4, 2, 5, 3, 6, 1, 2, 1, 3, 2, 8, 9, 7]
print(num.count(3))
Python

The Output Of This Code Will Be:

Output
2
3
Python

5. `copy()` Method:

colors = ["voilet", "green", "indigo", "blue"]
newlist = colors.copy()
print(colors)
print(newlist)
Python

The Output Of This Code Will Be:

Output
['voilet', 'green', 'indigo', 'blue']
['voilet', 'green', 'indigo', 'blue']
Python

6. `append()` Method:

colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)
Python

The Output Of This Code Will Be:

Output
["voilet", "indigo", "blue", "green"]
Python

7. `insert()` Method:

Insert an item at the given index.

colors = ["voilet", "indigo", "blue"]
colors.insert(1, "green")
print(colors)
Python

The Output Of This Code Will Be:

Output
['voilet', 'green', 'indigo', 'blue']
Python

8. `extend()` Method:

Adds an entire list or any other collection datatype to the existing list.

colors = ["voilet", "indigo", "blue"]
rainbow = ["green", "yellow", "orange", "red"]
colors.extend(rainbow)
print(colors)
Python

The Output Of This Code Will Be:

Output
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
Python

9. Concatenating two lists

colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)
Python

The Output Of This Code Will Be:

Output
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
Python

If you don’t know the “Functions in Python” just click on read more.

I hope you understand “Lists and List Methods in Python”  Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog