Python List
Python List
PYTHON LIST
Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
eg:
print(a)
List Items
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order,
and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a
list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Eg:
print(a)
List Length
To determine how many items a list has, use the len() function:
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
#Accessing elements from list
Positive indexing
a=[21,22,"welcome","cat",30.5]
print(a[0])
Negative indexing
a=[21,22,"welcome","cat",30.5]
print(a[-1])
Range with Slicing a list
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[2:5])
b= ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(b[:4])
c = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(c[2:])
d = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(d[-4:-1])
a=[21,22,"welcome","cat",30.5]
print(a[2:4])
Changing the value of items in a list
a=[21,22,"welcome","cat",30.5]
print(a[2])
a[3]=1000
a[-3]="hello"
print(a[3])
print(a)
Add List Items
Append Items
To add an item to the end of the list, use the append() method:
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Extend List
To append elements from another list to the current list, use
the extend() method.
Sort Lists
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
Sort Descending
To sort descending, use the keyword argument reverse = True:
Join Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Another way to join two lists is by appending all the items from list2 into list1,
one by one:
Method Description
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value