Python Datatypes

Python List (With Examples)

The sequence is the most fundamental data structure in Python for storing multiple elements all at once. Each element of a series is given a number that represents its location or index. The first index is zero, the second one, and so on. Python contains six built-in sequence types, but the most frequent ones are lists and tuples. In this article, we will cover the entire concept of the Python list.

Python List

Python Lists are similar to dynamically scaled arrays. They are used to hold a series of different formats of data. Python lists are changeable (mutable), which means they can have their elements changed after they are created. A Python list can also be defined as a collection of distinct types of values or items. The elements in the list are separated by using commas (,) and are surrounded by square brackets [].

A single list can contain Datatypes such as Integers, Strings, and Objects. Lists are changeable, which means they can be changed even after they are created. Each element in the list has a different location in the list, allowing for the duplication of components in the list, each with its own individual place and credibility.

How to create a list?

A Python list is generated in Python programming by putting all of the items (elements) inside square brackets [], separated by commas. It can include an unlimited number of elements of various data types (integer, float, string, etc.). Python Lists can also be created using the built-in list() method.

Example

                    

# Python program to create Lists
# creating empty list
my_list = []
print(my_list)

# creating list using square brackets
lang = ['Python', 'Java', 'C++', 'SQL']
print('List of languages are:', lang)

# creating list with mixed values
my_list = ['John', 23, 'Car', 45.2837]
print(my_list)

# nesting list inside a list
nested = ['Values', [1, 2, 3], ['Marks']]
print(nested)

# creating list using built-in function
print(list('Hello World'))

Output

                    

[]
List of languages are: ['Python', 'Java', 'C++', 'SQL']
['John', 23, 'Car', 45.2837]
['Values', [1, 2, 3], ['Marks']]
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Access List Elements

The elements of a list can be accessed in a variety of ways.

  • List Index

Lists are ordered sequences of elements that, like all other ordered containers in Python, are indexed with a starting index of 0. We supply the index (an integer) inside square brackets ([]) to access an element in a list. Nested indexing is used to retrieve nested listings.

Attempting to access indexes beyond the limit will result in an IndexError. The index must be a positive integer. We can’t use floats or other kinds because it will cause a TypeError.

Example

                    

# Python program to illustrate List Indexing
my_list = ['A', 'B', 'Car', 'Dog', 'Egg']

print('List value at index 1:', my_list[1])
print('List value at index 2:', my_list[2])
print('List value at index 4:', my_list[4])

# nesting list
nested = ['Values', [1, 2, 3], ['Marks']]
print(nested[0][0])
print(nested[1][0])
print(nested[1][2])
print(nested[2][0])

# IndexError exception
print(my_list[10])

Output

                    

List value at index 1: B
List value at index 2: Car
List value at index 4: Egg
V
1
3
Marks
Traceback (most recent call last):
  File "", line 16, in 
IndexError: list index out of range

  • Negative Indexing

Negative sequence indexes in Python represent positions from the array’s end. Python sequences support negative indexing. The value of -1 denotes the last item, the index of -2 the second last item, and so on.

Example

                    

# Python program to illustrate Negative Indexing
my_list = ['A', 2, 'Car', 'Dog', 'Egg', 100]

print(my_list[-1])
print(my_list[-3])
print(my_list[-6])

Output

How to slice lists in Python?

There are several ways to print the entire list with all of its elements in Python List, but we utilize the Slice operation to print a selected range of elements from the list. A colon is used to conduct the slice operation on Lists (:).

The syntax is as follows:

                    

list_name[start: stop: step]

where,

  • start – indicates the starting index position of the list to be sliced.
  • stop – the stop represents the list’s last index position.
  • step – the step function is used to skip the nth element in a start:stop

Example

                    

# Python program to illustrate List Slicing
my_list = ['P', 'y', 't', 'h', 'o', 'n', 1, 2, 3, 4]

# printing all elements
print(my_list[:])

# start slicing from 3
print(my_list[3:])

# start and end slicing from 2 to 5
print(my_list[2:5])

# all elements excluding last 3
print(my_list[:-3])

Output

                    

['P', 'y', 't', 'h', 'o', 'n', 1, 2, 3, 4]
['h', 'o', 'n', 1, 2, 3, 4]
['t', 'h', 'o']
['P', 'y', 't', 'h', 'o', 'n', 1]

Add/Change List Elements

Lists, unlike strings and tuples, are mutable, which means that their elements can be altered. There are few methods by which we can add or change the elements inside the list. They are as follows –

  • Using Assignment Operator

To alter an item or a range of elements, we can use the assignment operator ‘=’. We can change a list item by putting the index or indexes in square brackets on the left side of the assignment operator (like we access or slice a list) and the new values on the right.

Example

                    

names = ['Ricky', 'Tim', 23, 100.23, 'Sam', 'Emily']
print('Original List:', names)

names[2] = 'Lily'
print('Updated List:', names)

names[3] = 'Han'
print('Updated List:', names)

names[1:5] = ['A', 'B', 'C', 'D']
print('Updated List:', names)

Output

                    

Original List: ['Ricky', 'Tim', 23, 100.23, 'Sam', 'Emily']
Updated List: ['Ricky', 'Tim', 'Lily', 100.23, 'Sam', 'Emily']
Updated List: ['Ricky', 'Tim', 'Lily', 'Han', 'Sam', 'Emily']
Updated List: ['Ricky', 'A', 'B', 'C', 'D', 'Emily']

  • Using append() & extend() method

The built-in append() function can be used to add elements to the List. The append() method can only add one element to the list at a time. We can use the extend() function to add multiple elements to the list.

Example

                    

num = [1, 2, 3, 4]
print('Original List:', num)

num.append(5)
print(num)

num.extend([6, 7, 8])
print(num)

Output

                    

Original List: [1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]

  • Using insert() method

We can insert one item at a time using the insert() method, or we can insert numerous things by squeezing them into an empty slice of a list. Unlike the append() function, which accepts only one argument, insert() function requires two arguments -> (position, value)

Example

                    

num = [1, 2, 5, 6]
print('Original List:', num)

num.insert(2, 3)
print(num)

num.insert(3, 4)
print(num)

Output

                    

Original List: [1, 2, 5, 6]
[1, 2, 3, 5, 6]
[1, 2, 3, 4, 5, 6]

Delete/Remove List Elements

There are three methods for eliminating items from a list:

  • Keyword del

Using the keyword del, we can remove one or more entries from a list. It has the ability to completely remove the list.

                    

num = [1, 2, 3, 4, 5, 6]
print('Original List:', num)

# delete one item
del num[2]
print(num)

# delete multiple items
del num[3:5]
print(num)

# delete entire list
del num
print(num)

Output

                    

Original List: [1, 2, 3, 4, 5, 6]
[1, 2, 4, 5, 6]
[1, 2, 4]
Traceback (most recent call last):
  File "", line 14, in 
NameError: name 'num' is not defined

  • Using remove() method

The Python remove() method returns None after removing the first matching element from the list. A ValueError exception is thrown if the element is not found in the list.

                    

num = ['p', 'y', 't', 'h', 'o', 'n']
print('Original List:', num)

num.remove('t')
print(num)

num.remove('n')
print(num)

Output

                    

Original List: ['p', 'y', 't', 'h', 'o', 'n']
['p', 'y', 'h', 'o', 'n']
['p', 'y', 'h', 'o']

  • Using the pop() method

The pop() function can also be used to delete and return a list element. If no index is specified, the Python pop() method removes and returns the list’s final item. When attempting to remove an index that is outside the range of the list, an IndexError is raised.

                    

tech = ['Mobile', 'Laptop', 'AI', '5G', 'ML']
print('Original List:', tech)

print('Item popped:', tech.pop(1))
print(tech)

print('Item popped:', tech.pop())
print(tech)

Output

                    

Original List: ['Mobile', 'Laptop', 'AI', '5G', 'ML']
Item popped: Laptop
['Mobile', 'AI', '5G', 'ML']
Item popped: ML
['Mobile', 'AI', '5G']

  • Assign an empty list to a slice

Also by assigning an empty list to a slice of elements, we can delete elements from a list. For example,

                    

alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print('Original List:', alpha)

alpha[1:5] = []
print(alpha)

Output

                    

Original List: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'f', 'g']

Python List Methods

The methods accessible with list objects in Python programming are listed below. They are referred to as list.method().

Methods Description
append() Adds a single element to the end of the list
clear() Removes all the elements from the list
copy() Returns a shallow copy of the list
count() Returns the number of items specified as a parameter
extend() Adds multiple elements to the end of the list
index() Returns the index value of the first matched item
insert() Inserts an item at the specified index position
pop() Returns and removes an element at the specified index
remove() Removes a specified item from the list
reverse() Reverses the order of the entire list
sort() Sorts all the items in an ascending order

Example

                    

num = [2, 8, 6, 4, 12, 10, 0]
print('Original List:', num)

print('Index value of element 4 is:', num.index(4))

num.reverse()
print('Reversed List:', num)

num.sort()
print('Sorted List:', num)

Output

                    

Original List: [2, 8, 6, 4, 12, 10, 0]
Index value of element 4 is: 3
Reversed List: [0, 10, 12, 4, 6, 8, 2]
Sorted List: [0, 2, 4, 6, 8, 10, 12]

List Comprehension: Elegant way to create Lists

List comprehensions are used to generate new lists from other iterables like tuples, strings, arrays, lists, and so on. A list comprehension is made of brackets that hold the expression that is run for each element, as well as the for loop that iterates through each element. Multiple for or if statements can be included in a list comprehension if desired.

Example

                    

odd_squares = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_squares)

a = [x+y for x in ['Clean ', 'Green '] for y in ['World', 'Day']]
print(a)

Output

                    

[1, 9, 25, 49, 81]
['Clean World', 'Clean Day', 'Green World', 'Green Day']

Other List Operations in Python

  • List Membership Test

Membership operators are used to validating a value’s membership. It checks for sequence membership, such as strings, lists, or tuples. Using the keywords “in” and “not in”, we can determine whether or not an item exists in a list.

Example

                    

my_list = ['P', 'r', 'o', 'g', 'r', 'a', 'm']

print('P' in my_list)

print('x' in my_list)
 
print('c' not in my_list)

Output

                    

True
False
True

  • Iterating Through a List

We can iterate through each item in a list using a for loop.

                    

fruits = ['apple', 'mango', 'banana', 'pineapple']

for f in fruits:
    print('I like', f)

Output

                    

I like apple
I like mango
I like banana
I like pineapple

Frequently Asked Questions

Q1. What is a list in Python?

Python Lists are similar to dynamically scaled arrays. They are used to hold a series of different formats of data. Python lists are changeable (mutable), which means they can have their elements changed after they are created. A list can also be defined as a collection of distinct types of values or items. The elements in the list are separated by using commas (,) and are surrounded by square brackets [].

A single list can contain Datatypes such as Integers, Strings, and Objects. Lists are changeable, which means they can be changed even after they are created.

Q2. How do I create a list in Python?

A list is generated in Python programming by putting all of the items (elements) inside square brackets [], separated by commas. It can include an unlimited number of elements of various data types (integer, float, string, etc.). Python Lists can also be created using the built-in list() method.

Example

                    

# Python program to create Lists
# creating empty list
my_list = []
print(my_list)

# creating list using square brackets
lang = ['Python', 'Java', 'C++', 'SQL']
print('List of languages are:', lang)

# creating list with mixed values
my_list = ['John', 23, 'Car', 45.2837]
print(my_list)

# creating list using built-in function
print(list('Hello World'))

Output

                    

[]
List of languages are: ['Python', 'Java', 'C++', 'SQL']
['John', 23, 'Car', 45.2837]
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.