Lists in Python

Lists

Lists are used to store data of different data types in a sequential manner and there are addresses assigned to every element, called index.

Creating a List

To create a list, you use square brackets and add elements into it accordingly.

# Create empty list
my_list = [] 
print(my_list)

# Create list with elements
my_list = [1, 2, 3, 'example', 3.132]
print(my_list)

# Output:
# []
# [1, 2, 3, 'example', 3.132]

Accessing Elements

Accessing element, you should pass the index values and hence can obtain value.

my_list = [1, 2, 3, 'example', 3.132, 10, 30]

# Access one by one
for element in my_list:
    print(element)
    
# Access all elements
print(my_list)

# Access index 3 element
print(my_list[3])

# Access from 0 to 1, exclude 2
print(my_list[0:2])

# Access elements in reverse
print(my_list[::-1])

# Output:
# 1
# 2
# 3
# example
# 3.132
# 10
# 30
# [1, 2, 3, 'example', 3.132, 10, 30]
# example
# [1, 2]
# [30, 10, 3.132, 'example', 3, 2, 1]

Deleting Elements from List

To delete elements, use the del keyword which does not return anything back.

my_list = [1, 2, 3, 'example', 3.132, 10, 30]

# Delete element at index 5
del my_list[5]
print(my_list)

# Pop element from list
a = my_list.pop()
print('Popped Element:', a)

# Empty the list
my_list.clear()
print(my_list)

# Output:
# [1, 2, 3, 'example', 3.132, 30]
# Popped Element: 30
# []