Python List

In Python lists allows us to store a sequence of items in a single variable.

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]

				
			

List Characteristics

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 a index.

The index always starts from 0. The first element of a list is at index 0, the second element is at index 1, and so on.

				
					List → ['Python', 'Swift', 'C++']
Index →  0         1        2

          Index of List Elements
				
			

Negative Indexing in Python

Python also supports negative indexing. The index of the last element is -1, the second-last element is -2, and so on.

                              [‘Python’, ‘Swift’, ‘C++’]
                 Index → 0            1          2

Negative Index → -3         -2         -1

Python Negative Indexing

Negative indexing makes it easy to access list items from last.

Let’s see an example,

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

# access item at index 0
print(languages[-1])   # C++

# access item at index 2
print(languages[-3])   # Python

				
			

Slicing of a List in Python

In Python, it is possible to access a section of items from the list using the slicing operator :. For example,

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

# items from index 2 to index 4
print(my_list[2:5])

# items from index 5 to end
print(my_list[5:])

# items beginning to end
print(my_list[:])

				
			
Output:
				
					['o', 'g', 'r']
['a', 'm']
['p', 'r', 'o', 'g', 'r', 'a', 'm']