Understanding Lists
Lists are the most versatile data structure used in Python. Lists store the data elements
sequentially and can be accessed by indexing. Indexing in lists start with “0” as the first index.
What’s make the Lists so powerful is, lists support different types of data types.
Lists are mutable, which means they can be modified after their creation unlike string.
Creating Lists in Python
A list in python is created by placing all the elements inside the square
brackets [] with
comma separated.
list = [1, 2, “item”, 2.0]
list[2] = “mutable” // lists are mutable and zero based index
print(list)
nested_list = [1, 2, [4, 5], 6] // list stores list inside it.
print(nested_list)
Output:
[1, 2, “mutable”, 2.0]
[1, 2, [4, 5], 6]
Negative Indexing in Lists
Unlike other data structures in other programming languages, Lists support
negative
indexing which means, you can access the elements of list with negative indices too.
list = [1, 2, 3, 4, 5, 6]
print(list[-1])
print(list(-3))
Output:
6
4
Slicing Lists
Slicing of list allows you to access the range of elements in the list.
Syntax:
list[start index : end index : gap]
it gives the elements starting from index “start index” to one before “end index” with gap between indices.
By default, gap =1
list[1, 2, 3, 4, 5, 6]
print(list[1 : 4])
print(list[ :])
print(list[1 : 4 : 2]) // here gap = 2, means jump to index + 2 from index
Output:
[2, 3, 4]
[1, 2, 3, 4, 5, 6]
[2, 4]
Helpful and nice content
ReplyDeleteThank you for your feedback!
DeleteExplanation is good
ReplyDeleteThanks for your feedback and support.
DeleteGood
ReplyDeleteThanks for your feedback!
DeleteI want to create a list which enforce data type into it, so that it doesn't accept other data type values by mistake like array in other strictly types languages
ReplyDeleteNo,in Python's list you cannot restrict to store values of single type of data type and list is one of the primary data type in python that stores any type of data even simultaneously.
Delete