0% found this document useful (0 votes)
3 views11 pages

Python List

This document provides an overview of Python lists, explaining their creation, characteristics, and methods for accessing and manipulating list elements. It covers topics such as list indexing, slicing, adding and removing items, and built-in methods for list operations. The document emphasizes the flexibility of lists in storing different data types and their mutable nature.

Uploaded by

hananakamura699
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Python List

This document provides an overview of Python lists, explaining their creation, characteristics, and methods for accessing and manipulating list elements. It covers topics such as list indexing, slicing, adding and removing items, and built-in methods for list operations. The document emphasizes the flexibility of lists in storing different data types and their mutable nature.

Uploaded by

hananakamura699
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python List

In Python, lists allow us to store multiple items in a single variable. For


example, if you need to store the ages of all the students in a class, you
can do this task using a list.

Lists are similar to arrays (dynamic arrays that allow us to store items of
different data types) in other programming languages.

Create a Python List

We create a list by placing elements inside square brackets [], separated


by commas. For example,

# a list of three elements

ages = [19, 26, 29]

print(ages)

Output

[19, 26, 29]

Here, the ages list has three items.

List Items of Different Types

Python lists are very flexible. We can also store data of different data
types in a list. For example,

# a list containing strings, numbers and another list

student = ['Jack', 32, 'Computer Science', [2, 4]]

print(student)
# an empty list

empty_list = []

print(empty_list)

List Characteristics

In Python, lists are:

• Ordered - They maintain the order of elements.

• Mutable - Items can be changed after creation.

• Allow duplicates - They can contain duplicate values.

Access List Elements

Each element in a list is associated with a number, known as an index. The


index of first item is 0, the index of second item is 1, and so on.

Index of List Elements

We use these indices to access items of a list.

For example,

languages = ['Python', 'Swift', 'C++']

# access the first element


print('languages[0] =', languages[0])

# access the third element

print('languages[2] =', languages[2])

Output

languages[0] = Python

languages[2] = C++

Access List Elements

Negative Indexing

In Python, a list can also have negative indices. The index of the last
element is -1, the second last element is -2 and so on.

Python Negative Indexing

Let's see an example.

languages = ['Python', 'Swift', 'C++']


# access the last item

print('languages[-1] =', languages[-1])

# access the third last item

print('languages[-3] =', languages[-3])

Output

languages[-1] = C++

languages[-3] = Python

Slicing of a List in Python

If we need to access a portion of a list, we can use the slicing operator, [:]
For example,

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

print("my_list =", my_list)

# get a list with items from index 2 to index 4 (index 5 is not included)

print("my_list[2: 5] =", my_list[2: 5])

# get a list with items from index 2 to index -3 (index -2 is not included)

print("my_list[2: -2] =", my_list[2: -2])

# get a list with items from index 0 to index 2 (index 3 is not included)

print("my_list[0: 3] =", my_list[0: 3])

Output

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


my_list[2: 5] = ['o', 'g', 'r']

my_list[2: -2] = ['o', 'g', 'r']

my_list[0: 3] = ['p', 'r', 'o']

Add Elements to a Python List

As mentioned earlier, lists are mutable and we can change items of a list.
To add an item to the end of a list, we can use the list append() method.
For example,

fruits = ['apple', 'banana', 'orange']

print('Original List:', fruits)

[Link]('cherry')

print('Updated List:', fruits)

Output

Original List: ['apple', 'banana', 'orange']

Updated List: ['apple', 'banana', 'orange', 'cherry']

Add Elements at the Specified Index

We can insert an element at the specified index to a list using


the insert() method. For example,

fruits = ['apple', 'banana', 'orange']

print("Original List:", fruits)


[Link](2, 'cherry')

print("Updated List:", fruits)

Output

Original List: ['apple', 'banana', 'orange']

Updated List: ['apple', 'banana', 'cherry', 'orange']

Add Elements to a List From Other Iterables

The list extend() method method all the items of the specified iterable,
such as list, tuple, dictionary or string , to the end of a list. For example,

numbers = [1, 3, 5]

print('Numbers:', numbers)

even_numbers = [2, 4, 6]

print('Even numbers:', numbers)

# adding elements of one list to another

[Link](even_numbers)

print('Updated Numbers:', numbers)


Output

Numbers: [1, 3, 5]

Even numbers: [2, 4, 6]

Updated Numbers: [1, 3, 5, 2, 4, 6]

Change List Items

We can change the items of a list by assigning new values using


the = operator. For example,

colors = ['Red', 'Black', 'Green']

print('Original List:', colors)

# change the first item to 'Purple'

colors[0] = 'Purple'

# change the third item to 'Blue'

colors[2] = 'Blue'

print('Updated List:', colors)

Output

Original List: ['Red', 'Black', 'Green']

Updated List: ['Purple', 'Black', 'Blue']

Here, we have replaced

• the element at index 0 to 'Purple'


• the element at index 2 to 'Blue'

Remove an Item From a List

We can remove the specified item from a list using the remove() method.
For example,

numbers = [2,4,7,9]

# remove 4 from the list

[Link](4)

print(numbers)

Output

[2, 7, 9]

Remove One or More Elements of a List

Instead of using the remove() method, we can delete an item from a list
using the del statement. The del statement can also be used to delete
multiple elements or even the entire list.

names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']

# delete the item at index 1

del names[1]

print(names)

# delete items from index 1 to index 2

del names[1: 3]
print(names)

# delete the entire list

del names

# Error! List doesn't exist.

print(names)

Output

['John', 'Laura', 'Nick', 'Jack']

['John', 'Jack']

Traceback (most recent call last):

File "", line 15, in

NameError: name 'names' is not defined

Python List Length

To find the number of elements (length) of a list, we can use the built-
in len() function. For example,

cars = ['BMW', 'Mercedes', 'Tesla']

print('Total Elements:', len(cars))

Output

Total Elements: 3
Python List Methods

Python has many useful list methods that make it really easy to work with
lists.

Method Description

append() Adds an item to the end of the list

Adds items of lists and other iterables


extend()
to the end of the list

insert() Inserts an item at the specified index

Removes the specified value from the


remove()
list

Returns and removes item present at


pop()
the given index

clear() Removes all items from the list

Returns the index of the first matched


index()
item

Returns the count of the specified item


count()
in the list
Sorts the list in ascending/descending
sort()
order

reverse() Reverses the item of the list

copy() Returns the shallow copy of the list

You might also like