CBSE Class 11: Python List 1

Python List

  • How to create a list?
  • How to access elements from a list?
    • List Index
    • Negative Indexing
  • How to slice lists in Python?
  • How to change or add elements to a list?
  • How to delete or remove elements from a list?
  • Python List Methods
  • List Comprehension
  • Other List Operations in Python
    • List Membership Test
    • Iterating Through a List
    • Built-in Functions with List

Python offers a range of compound data types often referred to as sequences. List is one of the most frequently used and very versatile data type used in Python.

 

How to create a list?

In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.).

# To create an empty list
n = []

n=[]
print(type(n))
print(n)

Output

<class ‘list’>
[]

# To create a list of integers
n = [1, 2, 3]

# To create a list of float values
n = [1.45, 2.23, 3.98]

n = [1, 2, 3]
print(type(n))
print(n)

n = [1.45, 2.23, 3.98]
print(type(n))
print(n)

Output:

<class ‘list’>
[1, 2, 3]
<class ‘list’>
[1.45, 2.23, 3.98]

# list with mixed datatypes
n = [1, “Hello”, 3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list
n = [“hello”, [8, 4, 6], [‘a’]]

n = [1, "Hello", 3.4]
print(type(n))
print(n)

n = ["hello", [8, 4, 6], ['a']]
print(type(n))
print(n)

Output:

<class ‘list’>
[1, ‘Hello’, 3.4]
<class ‘list’>
[‘hello’, [8, 4, 6], [‘a’]]