Properties of Lists
Published by
sanya sanya
Python's lists - a fundamental data structure in computer science that enables you to store and organize multiple elements in one variable. Lists are like containers that can hold different types of data such as numbers, strings, and even other lists! Think of lists like a backpack that you carry around - it can hold your books, your laptop, your phone, and anything else you need to carry.
To understand lists, let's consider an analogy. Imagine that you are a chef, and you have to prepare a dish that requires several ingredients. You need to have all the ingredients in one place so that you can easily access them and combine them to create the final dish. Similarly, lists allow you to store different types of data in one place so that you can easily access and manipulate them.
Creating a List
- Lists are created using square brackets [ ].
- List is a heterogeneous as well as homogeneous data structure.
- List can store numerical, string, boolean data types.
Examples of lists:
-
**To create a list of numbers **- Suppose you need to store the scores of all the students in your class. You can create a list of numbers using the following syntax:
Scores = [80,75,95,70,68] #list containing scores of class print(Scores)
Output
[80,75,95,70,68]
-
To create a list of Strings - Let's say you need to store the names of all the students in your class. You can create a list of strings using the following syntax:
names = ["John", "Jane", "Mike", "Sara", "David"] print(names)
Output
['John', 'Jane', 'Mike', 'Sara', 'David']
-
Heterogeneous List
my_list = [1, 2.5, "apple", True] print(my_list)
Output
[1, 2.5, 'apple', True]
Accessing a List Item
-
Indexing
List follows zero (0) Indexing. It means the first item stored in the list is termed as index 0 element, second item is termed as index 1 item and so on. In Python, you can access elements of a list using their index position. The index starts at 0 for the first element and increases by 1 for each subsequent element.
To access a single element of a list, you can use square brackets [] and the index of the element you want to access. For example, consider the following list:
You can access first, second, third and so on elements of the list in the following ways,
fruits = ['apple', 'banana', 'cherry', 'grapes', 'mango'] #List of strings print(fruits[0]) # Output: 'apple' print(fruits[1]) # Output: 'banana' print(fruits[2]) # Output: 'cherry' print(fruits[3]) # Output: 'grapes'
Output
apple banana cherry grapes
-
Negative Indexing
You can also use negative indexing to access elements from the end of the list. The last element of the list has an index of -1, the second-to-last element has an index of -2, and so on. For example, to access the last element of the list, you can use the following code:
print(fruits[-1]) # Output: 'mango' print(fruits[-2]) # Output: 'grapes'
Output
mango grapes
-
Slicing in List
You can also use slicing to access a range of elements in a list. Slicing allows you to specify a starting index, an ending index (exclusive), and an optional step size. For example, to access the first two elements of the list, you can use the following code:
print(fruits[0:2]) # Output: ['apple', 'banana'] print(fruits[1:3]) # Output: ['banana','cherry']
Output
['apple', 'banana'] ['banana', 'cherry']
Nested Lists
Lists can also be used to store other lists! This is called a 2D list. For example, suppose you need to store the scores of all the students in your class for two different subjects. You can create a 2D list using the following syntax:
scores = [[90, 85], [92, 78], [80, 85], [75, 92], [88, 90]] print(scores)
Output
[[90, 85], [92, 78], [80, 85], [75, 92], [88, 90]]
Now, you can access each score individually using two indices. For example,
scores[1][0] will give you the score of the second student in the first subject, which is 92.
Operations on list
In Python, lists are a versatile data structure that supports a wide range of operations. Here are some of the common operations you can perform on lists:
-
Adding elements:
You can add elements to a list using the append() method, which adds an element to the end of the list. For example, **fruits.append('orange') **adds the string 'orange' to the end of the list.
# create a list of fruits fruits = ['apple', 'banana', 'cherry', 'grapes'] # add a new fruit to the list fruits.append('orange') # print the updated list of fruits print(fruits) # Output: ['apple', 'banana', 'cherry', 'Grapes', 'orange' ]
-
Removing elements:
You can remove elements from a list using the remove() method, which removes the first occurrence of the specified element from the list. For example, **fruits.remove('banana') **removes the string 'banana' from the list.
# create a list of fruits fruits = ['apple', 'banana', 'orange', 'kiwi'] # remove the fruit 'banana' from the list fruits.remove('banana') # print the updated list of fruits print(fruits) # Output: ['apple', 'orange', 'kiwi']
-
Sorting elements:
You can sort the elements in a list using the sort() method, which sorts the list in ascending order by default. For example, **numbers.sort() **sorts the list in ascending order.
# create a list of numbers numbers = [5, 2, 8, 1, 6] # sort the list of numbers in ascending order numbers.sort() # print the sorted list of numbers print(numbers) # Output: [1, 2, 5, 6, 8]
-
Reversing elements:
You can reverse the order of the elements in a list using the reverse() method. For example, **letters.reverse() **reverses the order of the elements in the list.
# create a list of letters letters = ['a', 'b', 'c', 'd'] # reverse the order of the letters in the list letters.reverse() # print the reversed list of letters print(letters) # Output: ['d', 'c', 'b', 'a']
-
Counting elements: You can count the number of occurrences of a specific element in a list using the count() method. For example, numbers.count(1) returns the number of times the number 1 appears in the list.
# create a list of numbers numbers = [1, 2, 3, 1, 4, 1, 5] # count the number of times the number 1 appears in the list count = numbers.count(1) # print the count of the number 1 print(count) # Output: 3
-
Length of list: You can find the length of a list using the len() function. For example, len(fruits) returns the number of elements in the list.
# Creates list of fruits fruits = ['apple', 'banana', 'cherry', 'grapes'] # get the length of the list of fruits length = len(fruits) # print the length of the list print(length) # Output: 4
-
Extend: Adds all the elements of a given iterable (e.g., list, tuple, set) to the end of the list.
my_list = [1, 2, 3] my_list.extend([4, 5, 6]) # my_list is now [1, 2, 3, 4, 5, 6]
-
Insert: Inserts an element at a specified index in the list.
my_list = [1, 2, 3] my_list.insert(1, "hello") # my_list is now [1, "hello", 2, 3]
-
Remove: Removes the first occurrence of an element from the list.
my_list = [1, 2, 3, 1] my_list.remove(1) # my_list is now [2, 3, 1]
-
Pop: Removes and returns the element at a specified index. If no index is specified, removes and returns the last element in the list.
my_list = [1, 2, 3] last_element = my_list.pop() # last_element is 3 and my_list is now [1, 2] second_element = my_list.pop(1) # second_element is 2 and my_list is now [1]
Using Loops in List
-
For Loop:
In this example, we create a list of names and then use a for loop to iterate through each name in the list. For each name, we print it to the console. Using a for loop with a list is useful when you want to perform the same action on each element in the list. For example, if you want to print all the elements of the list.
# create a list of names names = ['Alice', 'Bob', 'Charlie', 'David'] # iterate through the list using a for loop for name in names: # print each name print(name)
Output
Alice Bob Charlie David
-
While Loop:
A while loop is another type of loop in Python that can be used with lists, although it is not as commonly used with lists as the for loop. A while loop is used to repeat a block of code as long as a certain condition is true. Here's an example of how to use a while loop with a list:
# create a list of numbers numbers = [1, 2, 3, 4, 5] # create a variable to keep track of the index index = 0 # use a while loop to iterate through the list while index < len(numbers): # print each number print(numbers[index]) # increment the index by 1 index += 1
Output
1 2 3 4 5
In this example, we use a while loop to iterate through the list of numbers. We create a variable called index to keep track of which element in the list we're currently at, and we use a condition in the while loop to ensure that we only continue iterating as long as index is less than the length of the list (len(numbers)).
Inside the while loop, we print each number in the list by accessing it using the current value of index, and then we increment index by 1 so that we move on to the next element in the list.
Properties of Lists
- Ordered: The elements in a list are ordered, which means that you can access them by their index.
- Mutable: Unlike tuples, lists are mutable, which means that you can add, remove, or modify elements in a list.
- Heterogeneous: A list can contain elements of different data types.
- Iterable: You can iterate over the elements of a list using a loop.
- Indexable: You can access the elements of a list using their index.
- Nested: You can nest lists within other lists to create complex data structures.
Library
WEB DEVELOPMENT
FAANG QUESTIONS