Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
list

What is a Python list?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

A Python list is an ordered and changeable collection of data objects. Unlike an array, which can contain objects of a single type, a list can contain a mixture of objects.

svg viewer
A Python list of 5 objects.

As evident in the illustration above, a list can contain objects of any data type, including another list. This makes the list data structure one of the most powerful and flexible tools in Pythonic programming.

List creation

Defining a list in Python is really quite simple. The name of the list has to be specified, followed by the values it contains:

# Initiliazing a list with 5 objects
myList1 = [20, 'Edpresso', [1, 2, 3], 3.142, None]
print(myList1)
# Initializing an empty list
myList2 = []
print(myList2)

Accessing an element

A list element can be accessed using its index. The index is the position of an element in the list.

Similar to other languages, Python list elements are indexed from 0. This means that the first element will be at the 0 index.

To access an element, its index is enclosed in the [] brackets:

svg viewer
Accessing the fourth element in the list.
myIntList = [1,3,5,2,4]
print(myIntList[3]) # Accessing the 4th element

Adding and removing elements

The size of a list is not fixed. Elements can be added and removed at any point.

myList = ['a', 'b', 'c', 'd', 'e', 'f']
# Add an element at the end
myList.append('g')
print(myList)
# Insert element at a specific index
# insert(index, value)
myList.insert(3, 'z') # Insertion at the 3rd index
print(myList)
# Delete an element from the end
myList.pop()
print(myList)
# Delete the value at a specific index
del myList[1]
print(myList)
# Accessing the length of a list
print(len(myList))

RELATED TAGS

python
list
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring