0% found this document useful (0 votes)
4 views2 pages

Sorting Tuples Dictionaries in Python

The document explains sorting methods in Python, specifically the sort() method for in-place sorting and the sorted() function for returning a new sorted list. It also defines tuples as immutable ordered collections and highlights the differences between lists and tuples, noting that lists are mutable. Additionally, it describes dictionaries as collections of key-value pairs, emphasizing their unique keys and modifiable values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Sorting Tuples Dictionaries in Python

The document explains sorting methods in Python, specifically the sort() method for in-place sorting and the sorted() function for returning a new sorted list. It also defines tuples as immutable ordered collections and highlights the differences between lists and tuples, noting that lists are mutable. Additionally, it describes dictionaries as collections of key-value pairs, emphasizing their unique keys and modifiable values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Sorting Methods in Python

1. Using sort() Method


The sort() method sorts a list in place (modifies the original list) in ascending order. You
can use reverse=True to sort in descending order.

Example:

numbers = [5, 2, 8, 1, 3]
[Link]()
print(numbers) # Output: [1, 2, 3, 5, 8]

[Link](reverse=True)
print(numbers) # Output: [8, 5, 3, 2, 1]

2. Using sorted() Function


The sorted() function returns a new sorted list without modifying the original list.

Example:

numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]
print(numbers) # Original list remains unchanged

What are Tuples?


A tuple is an immutable (unchangeable) ordered collection of elements. Tuples are defined
using parentheses (). Since tuples cannot be modified, they are faster than lists.

Example:

my_tuple = (10, 20, 30, 'apple')


print(my_tuple) # Output: (10, 20, 30, 'apple')

Difference Between Lists and Tuples


Lists are mutable (can be changed), while tuples are immutable (cannot be changed). Lists
are defined using square brackets [], while tuples use parentheses ().

What are Dictionaries?


A dictionary is a collection of key-value pairs. Dictionaries are defined using curly brackets
{}. Each key is unique, and values can be modified.
Example:

student = {"name": "Alice", "age": 20, "grade": "A"}


print(student["name"]) # Output: Alice

You might also like