Ordered Data Structures in Python
Published by
sanya sanya
In Python, there are several built-in data structures that can be used to store and organize data. Two main categories of data structures are ordered and unordered data structures.
-
Ordered data structures:
An ordered data structure is a data structure where the elements are stored in a specific order. The order can be based on the position of the elements, the value of the elements, or both. Some of them are:
- Lists
- Tuples
- Strings
-
Unordered Data Structures:
An unordered data structure is a data structure where the elements are not stored in a specific order. Some of the unordered data structures in Python are:
- Sets
- Dictionaries
Let's discuss each ordered data structure type one by one.
-
Lists
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
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.
-
Tuples
A tuple is a collection of ordered, immutable objects. This means that once a tuple is created, its contents cannot be changed. Tuples are similar to lists, but unlike lists, they cannot be modified. This makes them useful for storing data that should not be changed, such as the dimensions of a rectangle or the RGB values of a color.
Analogy: Imagine you have a collection of different colored marbles. You can organize these marbles into sets based on their color, but once a marble is placed in a set, it cannot be moved to another set or changed in any way. Similarly, tuples allow you to organize and store data, but once a tuple is created, its contents cannot be modified.
Creating a Tuple
- Tuples are created using parentheses ( ).
- Tuples are a heterogeneous data structure.
- Tuples can store a variety of data types, including numerical, string, and boolean.
Examples of Tuples:
-
To create a tuple 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:
my_tuple = (100, 82, 95) print(my_tuple)
Output
(100, 82, 95)
-
To create a tuple of Strings - Let's say you need to store the names of fruits. You can create a list of strings using the following syntax:
my_tuple = ("apple", "banana", "orange") print(my_tuple)
Output
('apple', 'banana', 'orange')
-
Heterogenous tuples-
my_tuple = ("Hello, World!", 42, True) print(my_tuple) # Output: ('Hello, World!', 42, True)
Output
('Hello, World!', 42, True)
Accessing a Tuple Item
You can access individual elements of a tuple by their index, just like you would with a list. For example, to get the first element of a tuple, you would use tuple_name[0]. You can also slice a tuple using the same syntax as slicing a list.
my_tuple = (1, 2, 3, 4, 5) print(my_tuple[0]) # Output: 1 print(my_tuple[1:3]) # Output: (2, 3)
Output
1 (2, 3)
Nested Tuples
Nested tuples are tuples that contain other tuples as elements. This means that a single element of a tuple can be another tuple.
Here's an example of a nested tuple:
person = ("John", "Doe", (1980, 10, 15))
In this example, the person tuple contains three elements: the first name "John", the last name "Doe", and another tuple (1980, 10, 15) that represents the person's birthdate.
You can access the elements of a nested tuple by indexing the outer tuple and then indexing the inner tuple. For example, to get the month of the birthdate from the person tuple, you would use the following code:
month = person[2][1] print(month) # Output: 10
In this code, person[2] returns the inner tuple (1980, 10, 15), and person[2][1] accesses the second element of the inner tuple, which is the month.
Operations on Tuples
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:
In Python, tuples are immutable, which means you cannot add or remove elements from a tuple once it has been created. However, you can create a new tuple by concatenating two or more tuples together or by slicing an existing tuple.
You can concatenate two or more tuples using the + operator.
tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) tuple3 = tuple1 + tuple2 print(tuple3) # Output: (1, 2, 3, 4, 5, 6)
-
Removing elements: To remove an element from a tuple, you can use slicing to create a new tuple that excludes the element you want to remove. Here's an example:
old_tuple = (1, 2, 3, 4, 5) new_tuple = old_tuple[:2] + old_tuple[3:] print(new_tuple)
In this example, we create a tuple old_tuple with five elements. We then use slicing to create a new tuple new_tuple that includes all elements of old_tuple except the element at index 2 (which is the value 3). The + operator is used to concatenate the two slices of old_tuple. Finally, we print the contents of new_tuple to the console, which will be:
Output
(1, 2, 4, 5)
-
Multiplying Tuples : You can create a new tuple by multiplying an existing tuple with an integer. This will repeat the elements of the original tuple in the new tuple.
my_tuple = (1, 2, 3) new_tuple = my_tuple * 3 print(new_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
-
Unpacking Tuples : You can unpack a tuple into multiple variables by assigning the tuple to the variables.
my_tuple = (1, 2, 3) a, b, c = my_tuple print(a) # Output: 1 print(b) # Output: 2 print(c) # Output: 3
In this code, we create a tuple my_tuple with three elements (1, 2, 3). We then use a technique called tuple unpacking to assign the values of my_tuple to three separate variables a, b, and c.
The line a, b, c = my_tuple is where the tuple unpacking happens. This line is essentially equivalent to the following:
a = my_tuple[0] b = my_tuple[1] c = my_tuple[2]
-
Length of tuple : You can find the number of elements in a tuple using the len() function.
my_tuple = (1, 2, 3, 4, 5) print(len(my_tuple)) # Output: 5
-
Counting elements : In Python, you can count the number of occurrences of a specific element in a tuple using the count() method. The count() method returns the number of times the specified element appears in the tuple
my_tuple = (1, 2, 3, 4, 3, 2, 1) count_of_1 = my_tuple.count(1) print(count_of_1) # Output: 2
-
Reverse a Tuple : The reversed() function returns a reverse iterator, which can be used to loop through the elements of a tuple in reverse order. You can convert the reverse iterator to a tuple using the tuple() function.
my_tuple = (1, 2, 3, 4, 5) reversed_iterator = reversed(my_tuple) reversed_tuple = tuple(reversed_iterator) print(reversed_tuple)
Output
(5, 4, 3, 2, 1)
In this example, we create a tuple my_tuple with five elements. We then use the reversed() function to create a reverse iterator reversed_iterator and convert it to a tuple using the tuple() function. Finally, we print the contents of the reversed tuple to the console, which will be:
Using Loops in Tuples
-
For Loop: In this example, the for loop iterates over the elements of my_tuple and prints each element to the console. The output will be:
my_tuple = (1, 2, 3, 4, 5) for element in my_tuple: print(element)
Output
1 2 3 4 5
-
While Loop: Since tuples are immutable in Python, you cannot modify the contents of a tuple using a while loop. However, you can use a while loop to iterate over the elements of a tuple by converting it to a list first, using the list() function, and then converting it back to a tuple when you're done.
Here's an example:
my_tuple = (1, 2, 3, 4, 5) my_list = list(my_tuple) # Convert the tuple to a list i = 0 # Initialize a counter variable while i < len(my_list): # Iterate over the elements of the list print(my_list[i]) i += 1 my_tuple = tuple(my_list) # Convert the list back to a tuple
Output
1 2 3 4 5
In this example, the while loop iterates over the elements of the my_list and prints each element to the console. The i variable is used as a counter to keep track of the current index in the list. Once the loop is finished, the my_list is converted back to a tuple using the tuple() function.
It's worth noting that using a for loop with a tuple is generally a more Pythonic way to iterate over the elements of a tuple, since it's simpler and more efficient than converting the tuple to a list first. However, in some cases, a while loop may be more appropriate, such as when you need to perform more complex iteration logic or manipulate the index variable.
Properties of Tuples
- Immutable: Once a tuple is created, its elements cannot be changed. This means that you cannot add, remove, or modify elements in a tuple.
- Ordered: The elements in a tuple are ordered, which means that you can access them by their index.
- Heterogeneous: A tuple can contain elements of different data types.
- Iterable: You can iterate over the elements of a tuple using a loop.
- Indexable: You can access the elements of a tuple using their index.
- Nested: You can nest tuples within other tuples to create complex data structures.
- Hashable: Tuples are hashable, which means that they can be used as keys in dictionaries and elements in sets.
-
Strings
Strings are an important data type in Python that allow you to work with text-based data. In this blog post, we'll explore what strings are, how they work, and some common use cases for strings in Python.
Analogy: Strings are like a string of pearls. Each pearl represents a character in the string, and the order of the pearls determines the order of the characters in the string. Just as you can create different patterns and designs with a string of pearls, you can create different text-based data patterns with strings in Python.
Here are some examples of strings in Python:
my_string = "Hello, world!" print(my_string) # Output: "Hello, world!"
In this example, we create a string my_string that contains the text "Hello, world!". We then print the contents of the string to the console, which will be:
Output
Hello, world!
Here's another example of a string in Python:
name = "Alice" age = 25 greeting = f"Hello, my name is {name} and I am {age} years old." print(greeting) # Output: "Hello, my name is Alice and I am 25 years old."
In this example, we create a string greeting that contains a formatted message that includes the values of the variables name and age. We then print the contents of the string to the console, which will be:
Output
Hello, my name is Alice and I am 25 years old.
Similar to lists and tuples, strings also have several operations, properties etc.
Library
WEB DEVELOPMENT
FAANG QUESTIONS