List
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.
- List can contain duplicate items.
- List in Python are Mutable. Hence, we can modify, replace or delete the items.
- List are ordered. It maintain the order of elements based on how they are added.
- Accessing items in List can be done directly using their position (index), starting from 0
a = [10, 20, 15]
print(a[0]) # access first item
a.append(11) # add item
a.remove(20) # remove item
print(a)
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['apple', 'banana', 'cherry']
# Mixed data types
c = [1, 'hello', 3.14, True]
print(a)
print(b)
print(c)
Updating list
# Initialize an empty list
a = []
# Adding 10 to end of list
a.append(10)
print("After append(10):", a)
# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
# Adding multiple elements [15, 20, 25] at the end
a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)
# replace a list valuse
a[3] = 45
print(a)
# Remove a list item with value
a.remove(5)
#Remove a list item with Index
a.pop(2)
print(a)
# iterating through list
for item in a:
print(item)
Practise Programs
Create a list 10,20,30,40
- print Length of a List (using len function)
- print maximum value in a list (using max function)
- Swap two items in a list ( swap value in index 1 and 3) and print
- concatenate two list and print