Lists in Python
Python tutorial · PySpark.in
List
A list in Python is an ordered, mutable collection of items that can store multiple data types, such as integers, strings, or even other lists. Python lists are versatile and are one of the most commonly used data structures.
- Ordered: Items are stored in a specific sequence.
- Mutable: List can be modified by adding removing or changing elements.
- Allows duplicates: Same value can appear more than once.
- Supports Different Data Types: A list can hold a mix of strings, integers, floats, and more.
Example → ["Rohan", 22, 5.5, True]
Syntax
1. Creating a List:
Defining a list using square brackets [] and separating items with commas.
2. Accessing List Elements
You can access elements in a list using indexing. Remember, Python uses 0-based indexing.
3. Negative Indexing
You can also access elements from the end of the list using negative indexing. The index -1 refers to the last item, -2 to the second last, and so on.
4. Slicing a List
You can slice a list to extract a part of it using a range of indices.
5. Modifying a List
Since lists are mutable, you can change the values of existing items.
6. Adding Items to List
Python provides several methods to add items to a list.
append()->Add an item to end of the list.
insert()->Adds an item to at a specific postion.
extend()->Add multiple items from another list.
7. Removing Items
Python lists offer several methods to remove items:
remove()->Removes tge first occurrence of a specified value.
pop()-> Removes and returns an item at a specified index (default is the last item)
del()-> Deletes an item by index or deletes the entire list.
clear()-> Removes all items from the list, leaving it empty..
8. Looping Through List
Using a loop for to access each item one by one.
9. List Methods
Method | Description |
|---|---|
append() | Add item |
insert() | Insert at position |
extend() | Add list to list |
remove() | Remove item |
pop() | Remove index |
clear() | Empty list |
sort() | Sort list |
reverse() | Reverse list |
index() | Find index |
count() | Count item |
10. Sorting Lists
You can sort a list either in ascending or descending order.
Sort ascending
Sort descending
11. List Comprehension
List comprehension provides a concise way to create lists. It’s a compact version of for loops.
12. Nested Lists
A short, elegant way to create new lists using a single line of code.
13. Length of List
Returns the total number of items in the list.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges