English 中文(简体)
Lists Data Structure
  • 时间:2024-09-17

Lists Data Structure


Previous Page Next Page  

The Lists data structure is a versatile datatype in Python, which can be written as a pst of comma separated values between square brackets.

Syntax

Here is the basic syntax for the structure −

List_name = [ elements ];

If you observe, the syntax is declared pke arrays with the only difference that psts can include elements with different data types. The arrays include elements of the same data type. A pst can contain a combination of strings, integers and objects. Lists can be used for the implementation of stacks and queues.

Lists are mutable. These can be changed as and when needed.

How to implement psts?

The following program shows the implementations of psts −

my_pst = [ p , r , o , b , e ]
# Output: p
print(my_pst[0])

# Output: o
print(my_pst[2])

# Output: e
print(my_pst[4])

# Error! Only integer can be used for indexing
# my_pst[4.0]

# Nested List
n_pst = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a
print(n_pst[0][1])

# Output: 5
print(n_pst[1][3])

Output

The above program generates the following output −

List Data Structure

The built-in functions of Python psts are as follows −

    Append()− It adds element to the end of pst.

    Extend()− It adds elements of the pst to another pst.

    Insert()− It inserts an item to the defined index.

    Remove()− It deletes the element from the specified pst.

    Reverse()− It reverses the elements in pst.

    sort() − It helps to sort elements in chronological order.

Advertisements