List

List In Python

Introduction

“The beautiful thing about learning is that no one can take it away from you.”

This article will discuss a data type called list in python. We will also discuss, the creation, updating, modification, accessing, slicing, built-in methods, basic operators, etc with respect to the list.

Definition

The list is one of the most used primary data-type in python. A list is a collection of objects(int, float, string, boolean, list, tuple, dictionary, set, etc) stored in a single variable.

A list is similar to arrays in many other programming languages, except that array is a collection of only the same data type elements. Still, a list allows multiple data types inside a single list.

The syntax for creating a list

variable_name=[List of values separated by a comma]

Here, the list will be saved in a variable and can be used in the future.

Example

fruits=["apple","orange","pine-apple","grapes"]

Here, fruits is a list containing a list of fruits.

Accessing a list

Method 1- INDEXING

Every element in a list is accessed with the help of its index.

The first element in a list always has its index value of 0. So, if you want to retrieve the first element from the list we can write it as,

fruits=["apple", "orange", "pine-apple", "grapes"]
print(fruits[0])

The above program will retrieve the first element from the list.

If you need to retrieve the last element in a list, provided we don’t know how many elements are available, then we can use negative indexing.

The last element in a list always has its index value of -1.  So, if you want to retrieve the last element from the list we can write it as,

fruits=["apple", "orange", "pine-apple", "grapes"]
print(fruits[-1])

This will retrieve the last element in the list.

See also  Bank Management System in Python using Tkinter
Indexing

Method 2- Loop

For loop can be used to access the elements in a list one at a time.

fruits=["apple", "orange", "pine-apple", "grapes"]
for fruit in fruits:
  print(fruit)

In the above code snippet, 

  • Line 1, creates a list of fruits and saved it inside a variable called fruits.
  • Line 2, for loop, is written where we are accessing one element at a time. Here, the fruit variable holds one element at a time and executes the loop for all the elements. We are naming the iterating variable as fruit which is the singular form of the list for easy understanding.
  • Prints the value inside the fruit variable.

Method 3- Loop

For loop can be used in another way to access the elements with the index numbers.

fruits=["apple", "orange", "pine-apple", "grapes"]
for i in range(len(fruits)):
  print(i,"index has ",fruits[i])

Here, 

  • In Line 1, creates a list of fruits and saved it inside a variable called fruits.
  • Line 2, we write a for loop where the iteration has the numbers from 0 to the length of the list, which also acts as the index of the list.
  • Line 3, prints the index value(i) and the element.

Slicing

Slicing is a flexible tool to build a new list from the existing list. With help of slicing, you can access a few parts of the list.

Syntax

Lst[ Initial: End: IndexJump ]

Initial – This is the starting index, which is including the Initial index. By default, the value is 0.

End- This is the ending index, which is not included. By default, the value is the length of the list.

IndexJump- This is the skipping count, By default, the value is 1.

When everything is empty the whole list will be printed.

Example

number=[1,2,3,4,5,6,7,8,9]
print(number[::]) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
print(number[3:7]) #[4, 5, 6, 7]
print(number[2:9:3]) #[3, 6, 9]
print(number[:6:2]) #[1, 3, 5]
print(number[3::]) #[4, 5, 6, 7, 8, 9]

Updating the list

You can add elements to the list.

See also  While loop in python

append()

The append method is used to add a single element to a list at the end of the list.

fruits=["apple","orange","pine-apple","grapes"]
print("Before appending:",fruits)
fruits.append("water melon")
print("After appending: ",fruits)

Output:

Before appending: ['apple', 'orange', 'pine-apple', 'grapes']
After appending:  ['apple', 'orange', 'pine-apple', 'grapes', 'water melon']

extend()

The extend method is used to insert more than one value at the end of the list.

fruits=["apple","orange","pine-apple","grapes"]
print("Before appending:",fruits)
fruits.extend(["water melon","kiwi"])
print("After appending: ",fruits)

Output:

Before appending: ['apple', 'orange', 'pine-apple', 'grapes']
After appending:  ['apple', 'orange', 'pine-apple', 'grapes', 'water melon', 'kiwi']

insert()

The insert method is used to insert elements at any position in the list.

fruits=["apple","orange","pine-apple","grapes"]
print("Before appending:",fruits)
fruits.insert(1,"water melon")
print("After appending: ",fruits)

Output:

Before appending: ['apple', 'orange', 'pine-apple', 'grapes']
After appending:  ['apple', 'water melon', 'orange', 'pine-apple', 'grapes']

Here, the first parameter is the index where the element should be inserted.

Modify the elements

To modify the elements available in the list, we need to declare the index with the new value.

fruits=["apple","orange","pine-apple","grapes"]
print("Before modifing:",fruits)
fruits[2]="orange"
print("After modifing: ",fruits)

Output:

Before modifing: ['apple', 'orange', 'pine-apple', 'grapes']
After modifing:  ['apple', 'orange', 'orange', 'grapes']

Delete the elements

Del keyword

To delete a particular element in the list with the help of its index we can use del keyword.

fruits=["apple","orange","pine-apple","grapes"]
print("Before deleting:",fruits)
del fruits[2]
print("After deleting: ",fruits)

Output:

Before deleting: ['apple', 'orange', 'pine-apple', 'grapes']
After deleting:  ['apple', 'orange', 'grapes']

Here, the item at index 2 is deleted.

If we need to delete the whole list, we need to write del and list_name

fruits=["apple","orange","pine-apple","grapes"]
print("Before deleting:",fruits)
del fruits
print("After deleting: ",fruits)

Output:

Before deleting: ['apple', 'orange', 'pine-apple', 'grapes']
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print("After deleting: ",fruits)
NameError: name 'fruits' is not defined

remove()

The remove method is used to delete one particular element from the list. This can be used whenever we are not sure about the index of the list or if you want to delete the first occurrence of the element in the list.

fruits=["apple","orange","pine-apple","grapes","orange"]
print("Before deleting:",fruits)
fruits.remove("orange")
print("After deleting: ",fruits)

Output:

Before deleting: ['apple', 'orange', 'pine-apple', 'grapes', 'orange']
After deleting:  ['apple', 'pine-apple', 'grapes', 'orange']

pop()

The pop method is used to pop elements out of the list.

See also  Tuples in python

The pop method without parameters is used to pop the last added element outside the list.

fruits=["apple","orange","pine-apple","grapes","orange"]
print("Before deleting:",fruits)
fruits.pop()
print("After deleting: ",fruits)

Output:

Before deleting: ['apple', 'orange', 'pine-apple', 'grapes', 'orange']
After deleting:  ['apple', 'orange', 'pine-apple', 'grapes']

If we write the pop method with parameters then the index of that particular element will be popped out.

fruits=["apple","orange","pine-apple","grapes","orange"]
print("Before deleting:",fruits)
fruits.pop(2)
print("After deleting: ",fruits)

Output:

Before deleting: ['apple', 'orange', 'pine-apple', 'grapes', 'orange']
After deleting:  ['apple', 'orange', 'grapes', 'orange']

The difference between pop and del is that we can save the popped item in a variable and use it for further execution.

Clear()

The clear method is used to empty the elements in the list.

fruits=["apple","orange","pine-apple","grapes","orange"]
print("Before deleting:",fruits)
fruits.clear()
print("After deleting: ",fruits)

Output:

Before deleting: ['apple', 'orange', 'pine-apple', 'grapes', 'orange']
After deleting:  []

Basic list operations

Python expressionOutputDescription
len([1, 2, 3])3length
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]concatenation
[‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]repetition
3 in [1, 2, 3]Truemembership

Other built-in methods and function

NameExplanationExample
len(list)returns the total length of the list.number=[1,2,3,4,5,6,7,8,9]print(len(number))#9
max(list)Returns element from the list with max value.print(max(number))#9
min(list)Returns element from the list with max value.print(min(number))#1
list.count(obj)Returns the count of how many times the obj was present in a list.print(number.count(5))#1
list.index(obj)Returns the index of the first occurrence of the obj.print(number.index(6))#5
list.reverse()The list will be reversed and saved in the same list.number.reverse()print(number)#[9, 8, 7, 6, 5, 4, 3, 2, 1]
list.sort()The elements inside the list will be placed in ascending/descending order.number.sort()print(number)#[1, 2, 3, 4, 5, 6, 7, 8, 9]number.sort(reverse=True)print(number)#[9, 8, 7, 6, 5, 4, 3, 2, 1]

Practice yourself

  • Program to interchange the first and last element in the list.
  • Write a program to count unique values inside the list.
  • Create a game called seven lives,
    • Your game shows a secret word with its letters replaced by “?”
    • The player needs to guess the letters of the word, one at a time.
    • If the letter is guessed correctly, the question mark is replaced with the letter.
    • You will be given seven lives at the start of the game. For every incorrect guess, you lose one life.
    • The game ends once you have guessed the word correctly or have no lives left.

Conclusion

We have seen in detail about the list in python. You can fork and use this repl link to explore more about the list in python. You can write your doubts in the comments and can eagerly expect a reply from your friends. Learning is multiplied by sharing.

1 thought on “List In Python”

  1. Pingback: Tuples in python -

Leave a Comment

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

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock