List in python
What is list
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data,
Its mutable (you can edit it )
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist =
["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Access Items
list items are indexed and you can access them by referring to the
index number:
ExampleGet your own Python Server
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
Negative indexing means start from the end
-
refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and
where to end the range.
When specifying a range, the return value will be a new list with the
specified items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "m
ango"]
print(thislist[2:5])