A list in python is a data structure, to store a collection of elements with dynamic size in nature. The Elements are ordered in insertion order, mutable and allow duplicate values.
A list is a Data structure in Python similar to an Array with dynamic size.
It is a collection of mutable homogenous sequences of objects.
Features
- List elements are Dynamic in size
- A list is a collection of elements with duplicate values,
- Order is insertion order.
What are the advantages of Lists?
Sets store unique elements, and order is not preserved. Accessing the Set element to check whether an element exists or not is faster compared with List.
We can do mulple things with list
Create a List
Multiple ways to create a list in Python.
- Empty List
Empty list created with either square brackets or list() constructor.
# Using square brackets
empty_list1 = []
# Using list() constructor
empty_lists2 = list()
The empty list is a list with zero elements.
- Create a List with initial data
Elements are inserted into list while creating list.
# number types
numbers = [11,12,13]
# string types
strings = ['one','two','three']
list_with_multiple_types = [13, "test", 4.25, True, None]
Access elements of a list in Python
You can access the elements in a list using index.
The index can be a positive or negative number.
- if list contains 5 elements, and valid indexes to get elements are -5 to 4. Any other index values throw an error.
- The positive index count from begining of a list( first element index is 0)
- The negative index count from end of a list( last elemtn index is -1)
- first element’s index is 0, last element’s index is
len(list)-1or-1if counting from end
The below example list contains a size of 5. first element index is zero, last element index is 4.
numbers=[1,3,5,7,9];
print(numbers[0]) # 1
print(numbers[4]) # 9
If you access a list with an index greater than 4(index=5), It throws an IndexError: list index out of range error.
print(numbers[5]) # 9
Output:
Traceback (most recent call last):
File "C:\Users\Kiran\PycharmProjects\myapp\arraytest.py", line 4, in <module>
print(numbers[5]) # 9
~~~~~~~^^^
IndexError: list index out of range
List with negative index example:
numbers=[1,3,5,7,9];
print(numbers[-1]) # 9
print(numbers[-4]) # 3
print(numbers[-5]) # IndexError: list index out of range
How to find the size of an List in Python
List size is the number of elements in it. len(list) function returns an list length
numbers=[1,3,5,7,9];
print(len(numbers)) # 5
Array iterate elements using for in loop
numbers=[1,3,5,7,9];
for element in numbers:
print(element);