In Python, lists are versatile and powerful data structures used to store collections of items. They are fundamental to programming and offer a straightforward way to manage and manipulate data. In this guide, we’ll delve into the meaning of lists, explore examples to illustrate their usage, address common questions, and conclude with insights on their significance.
- Lists are ordered collection of data items.
- They store multiple items in a single variable.
- List items are separated by commas and enclosed within square brackets [].
- Lists are changeable meaning we can alter them after creation.
What is Lists in Python?
Lists are ordered collections of items that can hold various data types, such as numbers, strings, or even other lists. They allow for flexible storage and manipulation of data in Python programs.
Example:
Imagine a shopping list containing items like fruits, vegetables, and snacks. Each item in the list represents a different piece of information, and the list itself keeps everything organized in one place.
Example 1:
lst1 = [1,2,2,3,5,4,6]
lst2 = ["Red", "Green", "Blue"]
print(lst1)
print(lst2)
PythonOutput:
[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']
PythonExample 2:
details = ["Abhijeet", 18, "FYBScIT", 9.8]
print(details)
PythonOutput:
['Abhijeet', 18, 'FYBScIT', 9.8]
PythonAs we can see, a single list can contain items of different datatypes.
Python List Indexes
Each item/element in a list has its own unique index. This index can be used to access any particular item from the list. The first item has index [0], second item has index [1], third item has index [2] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
PythonAccessing list items in Python
1. Positive Indexing
As we have seen that list items have index, as such we can access items using these indexes.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
print(colors[2])
print(colors[4])
print(colors[0])
PythonOutput:
Blue
Green
Red
Python2. Negative Indexing
Similar to positive indexing, negative indexing is also used to access items, but from the end of the list. The last item has index [-1], second last item has index [-2], third last item has index [-3] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [-5] [-4] [-3] [-2] [-1]
print(colors[-1])
print(colors[-3])
print(colors[-5])
PythonOutput:
Green
Blue
Red
Python3. Check for item
We can check if a given item is present in the list. This is done using the in keyword.
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
if "Yellow" in colors:
print("Yellow is present.")
else:
print("Yellow is absent.")
PythonOutput:
Yellow is present.
PythonCopy
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
if "Orange" in colors:
print("Orange is present.")
else:
print("Orange is absent.")
PythonOutput:
Orange is absent.
Python4. Range of Index
You can print a range of list items by specifying where do you want to start, where do you want to end and if you want to skip elements in between the range.
Syntax:
List[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.
Example: printing elements within a particular range:
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[3:7]) #using positive indexes
print(animals[-7:-2]) #using negative indexes
PythonOutput:
['mouse', 'pig', 'horse', 'donkey']
['bat', 'mouse', 'pig', 'horse', 'donkey']
PythonHere, we provide index of the element from where we want to start and the index of the element till which we want to print the values.
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
PythonOutput:
['pig', 'horse', 'donkey', 'goat', 'cow']
['horse', 'donkey', 'goat', 'cow']
PythonWhen no end index is provided, the interpreter prints all the values till the end.
Example: printing all elements from start to a given index
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[:6]) #using positive indexes
print(animals[:-3]) #using negative indexes
PythonOutput:
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
PythonWhen no start index is provided, the interpreter prints all the values from start up to the end index provided.
Example: print alternate values
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes
PythonOutput:
['cat', 'bat', 'pig', 'donkey', 'cow']
['dog', 'mouse', 'horse', 'goat']
PythonHere, we have not provided start and index, which means all the values will be considered. But as we have provided a jump index of 2 only alternate values will be printed.
Example: printing every 3rd consecutive withing given range
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[1:8:3])
PythonOutput:
['dog', 'pig', 'goat']
PythonHere, jump index is 3. Hence it prints every 3rd element within given index.
Add List Items
There are three methods to add items to list: append(), insert() and extend()
1. Append()
This method appends items to the end of the existing list.
Example:
colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)
PythonOutput:
['voilet', 'indigo', 'blue', 'green']
PythonWhat if you want to insert an item in the middle of the python list? At a specific index?
2. Insert()
This method inserts an item at the given index. User has to specify index and the item to be inserted within the insert() method.
Example:
colors = ["voilet", "indigo", "blue"]
# [0] [1] [2]
colors.insert(1, "green") #inserts item at index 1
# updated list: colors = ["voilet", "green", "indigo", "blue"]
# indexs [0] [1] [2] [3]
print(colors)
PythonOutput:
['voilet', 'green', 'indigo', 'blue']
PythonCopy
What if you want to append an entire list or any other collection (set, tuple, dictionary) to the existing list?
3. Extend()
This method adds an entire list or any other collection datatype (set, tuple, dictionary) to the existing list.
Example 1:
#add a list to a list
colors = ["voilet", "indigo", "blue"]
rainbow = ["green", "yellow", "orange", "red"]
colors.extend(rainbow)
print(colors)
PythonOutput:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
PythonExample 2:
#add a tuple to a list
cars = ["Hyundai", "Tata", "Mahindra"]
cars2 = ("Mercedes", "Volkswagen", "BMW")
cars.extend(cars2)
print(cars)
PythonOutput:
['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'Volkswagen', 'BMW']
PythonExample 3:
#add a set to a list
cars = ["Hyundai", "Tata", "Mahindra"]
cars2 = {"Mercedes", "Volkswagen", "BMW"}
cars.extend(cars2)
print(cars)
PythonOutput:
['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'BMW', 'Volkswagen']
PythonExample 4:
#add a dictionary to a list
students = ["Sakshi", "Aaditya", "Ritika"]
students2 = {"Yash":18, "Devika":19, "Soham":19} #only add keys, does not add values
students.extend(students2)
print(students)
PythonOutput:
['Sakshi', 'Aaditya', 'Ritika', 'Yash', 'Devika', 'Soham']
Python4. Concatenate Two Lists
you can simply concatenate two list to join two lists.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)
PythonOutput:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
PythonRemove List Items
There are various methods to remove items from the list: pop(), remove(), del(), clear()
1. Pop()
This method removes the last item of the list if no index is provided. If an index is provided, then it removes item at that specified index.
Example 1:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop() #removes the last item of the list
print(colors)
PythonOutput:
['Red', 'Green', 'Blue', 'Yellow']
PythonExample 2:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop(1) #removes item at index 1
print(colors)
PythonOutput:
['Red', 'Blue', 'Yellow', 'Green']
PythonWhat if you want to remove a specific item from the list?
2. Remove()
This method removes specific item from the list.
Example:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.remove("blue")
print(colors)
PythonOutput:
['voilet', 'indigo', 'green', 'yellow']
PythonCopy
3. Del
del is not a method, rather it is a keyword which deletes item at specific from the list, or deletes the list entirely.
Example 1:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors[3]
print(colors)
PythonOutput:
['voilet', 'indigo', 'blue', 'yellow']
PythonExample 2:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors
print(colors)
PythonOutput:
NameError: name 'colors' is not defined
PythonWe get an error because our entire list has been deleted and there is no variable called colors which contains a list.
What if we don’t want to delete the entire list, we just want to delete all items within that list?
4. Clear()
This method clears all items in the list and prints an empty list.
Example:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.clear()
print(colors)
PythonOutput:
[]
PythonChange List Items
Changing items from list is easier, you just have to specify the index where you want to replace the item with existing item.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2] = "Millie"
print(names)
PythonOutput:
['Harry', 'Sarah', 'Millie', 'Oleg', 'Steve']
PythonYou can also change more than a single item at once. To do this, just specify the index range over which you want to change the items.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:4] = ["juan", "Anastasia"]
print(names)
PythonOutput:
['Harry', 'Sarah', 'juan', 'Anastasia', 'Steve']
PythonWhat if the range of the index is more than the list of items provided?
In this case, all the items within the index range of the original list are replaced by the items that are provided.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[1:4] = ["juan", "Anastasia"]
print(names)
PythonOutput:
['Harry', 'juan', 'Anastasia', 'Steve']
PythonWhat if we have more items to be replaced than the index range provided?
In this case, the original items within the range are replaced by the new items and the remaining items move to the right of the list accordingly.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:3] = ["juan", "Anastasia", "Bruno", "Olga", "Rosa"]
print(names)
PythonOutput:
['Harry', 'Sarah', 'juan', 'Anastasia', 'Bruno', 'Olga', 'Rosa', 'Oleg', 'Steve']
PythonPython List Comprehension
List comprehensions are used for creating new lists from other iterables like lists, tuples, dictionaries, sets, and even in arrays and strings.
Syntax:
List = [expression(item) for item in iterable if condition]
expression: it is the item which is being iterated.
iterable: it can be list, tuples, dictionaries, sets, and even in arrays and strings.
condition: condition checks if the item should be added to the new list or not.
Example 1: accepts items with the small letter “o” in the new list
names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)
PythonOutput:
['Milo', 'Bruno', 'Rosa']
PythonExample 2: accepts items which have more than 4 letters
names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if (len(item) > 4)]
print(namesWith_O)
PythonOutput:
['Sarah', 'Bruno', 'Anastasia']
PythonPython List Methods
We have discussed methods like append(), clear(), extend(), insert(), pop(), remove() before. Now we will learn about some more list methods:
1. Sort()
This method sorts the list in ascending order.
Example 1:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort()
print(num)
PythonOutput:
['blue', 'green', 'indigo', 'voilet']
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
PythonWhat if you want to print the python lists in descending order?
We must give reverse=True as a parameter in the sort method.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort(reverse=True)
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort(reverse=True)
print(num)
PythonOutput:
['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]
PythonThe reverse parameter is set to False by default.
Note: Do not mistake the reverse parameter with the reverse method.
2. Reverse()
This method reverses the order of the list.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.reverse()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.reverse()
print(num)
PythonOutput:
['green', 'blue', 'indigo', 'voilet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]
Python3. Index()
This method returns the index of the first occurrence of the list item.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.index("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.index(3))
PythonOutput:
1
3
Python4. Count():
Returns the count of the number of items with the given value.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.count("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
PythonOutput:
2
3
Python5. Copy()
Returns copy of the list. This can be done to perform operations on the list without modifying the original list.
Example:
colors = ["voilet", "green", "indigo", "blue"]
newlist = colors.copy()
print(colors)
print(newlist)
PythonOutput:
['voilet', 'green', 'indigo', 'blue']
['voilet', 'green', 'indigo', 'blue']
PythonConclusion
Python lists are indispensable tools for managing and organizing data in your programs. They offer flexibility, ease of use, and a wide range of functionalities for storing and manipulating collections of items. By mastering the basics of lists and exploring their capabilities, you unlock the potential to build more efficient and expressive Python programs. Embrace lists as your go-to data structure and unleash the power of organized data in your coding adventures.
FAQs
Ans: Yes, lists can hold a mix of data types, including numbers, strings, or even other lists.
Q2. What’s the Difference Between Lists and Arrays?
Ans: In Python, lists are dynamic and can hold elements of different types, while arrays are more rigid and typically contain elements of the same type.
Q3. How Do I Find the Length of a List?
Ans: You can use the len() function to determine the number of items in a list.print(len(shopping_list)) # Output: 4 (after modifications)