List- Python- Alpha Codist, adding ,removing elements from list, java, python, software, PHP, C programming, Alpha Codist, course, free, python list
Python List
In this article, we'll learn everything about Python lists, how they are created, slicing off a list, adding or removing elements from them, and so on.Python offers a range of compound data types. Which is often referred to as sequences. The list is one of the most frequently used and very versatile data types used in Python.
Create a list:
In Python programming, a list is created by placing all the items or elements inside square brackets [], separated by commas. It can have any number of items and they may be of different types (float, integer, string, etc.). And A list can also have another list as an item which is called a nested list.
Example:
# This is a list containing integer, float and string.
normal_list = [1, 54,65.56, "Alpha Codist", "python", "programming"]
# This is a list containing integer, float, string and a list.
nested_list = [1, 54,65.56, "Alpha Codist", ["python", "programming"]]
Indexing:
We can use the index operator [](brackets) to access an item in a list. In Python, indices start at 0. So, a list having 9 elements will have an index from 0 to 8.
Example:
# This is a list containing integer, float and string.
normal_list = [1, 54, 65.56, "Alpha Codist", "best", "good", "python", "programming"]
# The index of "Alpha Codist" will be 3
print(normal_list[3])
# the index of python will be -2 or 6
print(normal_list[-2])
# elements 3rd to 5th
print(normal_list[2:4])
# elements beginning to 4th
print(normal_list[:-5])
# elements 6th to end
print(normal_list[5:])
# elements beginning to end
print(normal_list[:])
Result:
Change elements from a list:
Example:
# This is a list containing integer, float and string.
normal_list = [1, 54,65.56, "Alpha Codist", "python", "programming"]
# This is a list containing integer, float, string and a list.
nested_list = [1, 54,65.56, "Alpha Codist", ["python", "programming"]]
print("List before adding 'coding'")
print(nested_list)
# adding elements in a list
nested_list.append("Coding")
print("List after adding 'coding'")
print(nested_list)
# This is a list containing integer, float and string.
normal_list = [1, 54,65.56, "Alpha Codist", "python", "programming"]
print("Before changing 65.56")
print(normal_list)
# The index of "Alpha Codist" will be 3
print(normal_list[3])
# Change an element
normal_list[2] = 'Coding'
print("After changing 65.56 to 'Coding'")
print(normal_list)
COMMENTS