fundamental of python : 3. Python Lists
fundamental of python
3. Python Lists
Python lists are one of the most fundamental and versatile data structures in the language. They are ordered, mutable sequences used to store collections of items, ranging from simple values like integers and strings to complex objects like other lists, dictionaries, or custom classes.
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Lists are created using square brackets;
Key Characteristics:
-
Ordered: Items in a list retain the order in which they are added. This allows for predictable access via indexing.
-
Mutable: Unlike strings and tuples, lists can be changed after creation. Items can be added, modified, or removed.
-
Heterogeneous Elements: A single list can hold elements of various data types, including numbers, strings, booleans, or even other lists.
Common Operations:
-
Accessing Elements:
-
Via indexing:
my_list[0]returns the first element. -
Via slicing:
my_list[1:4]retrieves a sublist containing elements from index 1 up to (but not including) index 4.
-
-
Modifying Contents:
-
Adding elements: Use
append(),insert(), orextend().-
Example:
my_list.append(10)
-
-
Removing elements: Use
remove(),pop(), ordel.-
Example:
my_list.pop(2)removes the third item.
-
-
Updating values directly via index:
-
Example:
my_list[0] = 100
-
-
-
Combining Lists:
-
Use the
+operator to concatenate lists.-
Example:
[1, 2] + [3, 4]results in[1, 2, 3, 4]
-
-
The
extend()method appends all elements of one list to another.
-
-
Nested Lists:
-
Lists can contain other lists, forming multi-dimensional structures useful for representing matrices, grids, or hierarchical data.
-
Example:
matrix = [[1, 2], [3, 4]]
-
-
Access nested elements using multiple indices:
matrix[1][0]returns3.
-
Additional Features:
-
List Comprehensions: A concise way to create lists using a single line of code.
-
Example:
[x**2 for x in range(5)]yields[0, 1, 4, 9, 16]
-
-
Built-in Functions: Lists support a range of useful functions like
len(),sorted(),min(),max(), andsum()when appropriate. -
Iteration: Lists are iterable, allowing them to be looped over with
foror comprehensions.
Use Cases:
- Storing sequences of data such as names, numbers, or objects.
- Implementing stacks, queues, and other custom data structures.
- Managing dynamic collections where items need to be added or removed frequently
Let’s walk through key list operations with examples:
🔹 1. Creating a List
Program:fruits = ['apple', 'orange', 'banana', 'mango']
type(fruits)Answer: <type 'list'>
Explanation: The variable fruits is a list containing four string elements.
🔹 2. Getting the Length of a List
Program:len(fruits)Answer: 4
Explanation: len() returns the number of elements in the list.
🔹 3. Accessing List Elements
Program:fruits[1]
Answer: 'orange'
fruits[1:3]
Answer: ['orange', 'banana']
fruits[1:]
Answer: ['orange', 'banana', 'mango']
Explanation:
- fruits[1] accesses the second item.
- fruits[1:3] slices the list from index 1 to 2.
- fruits[1:] gets all elements from index 1 to the end.
🔹 4. Appending an Item to a List
Program:
fruits.append('pear')fruitsAnswer: ['apple', 'orange', 'banana', 'mango', 'pear']
Explanation: append() adds a new element to the end of the list.
🔹 5. Removing an Item from a List
Program:fruits.remove('mango')fruitsAnswer: ['apple', 'orange', 'banana', 'pear']
Explanation: remove() deletes the first occurrence of the specified element.
🔹 6. Inserting an Item into a List
Program:fruits.insert(1, 'mango')
fruits
Answer: ['apple', 'mango', 'orange', 'banana', 'pear']
Explanation: insert(index, item) adds an element at the specified position.
🔹 7. Combining Two Lists
Program:vegetables = ['potato', 'carrot', 'onion', 'beans', 'radish']eatables = fruits + vegetableseatablesAnswer: ['apple', 'mango', 'orange', 'banana', 'pear', 'potato', 'carrot', 'onion', 'beans', 'radish']
Explanation: Using + combines two lists into a new one.
🔹 8. Mixed Data Types in a List
Program:type(mixed)Answer: <type 'list'>
type(mixed[0])Answer: <type 'str'>
type(mixed[1])Answer: <type 'int'>
type(mixed[2])Answer: <type 'float'>
type(mixed[3])Answer: <type 'long'> (python 2 only)
Explanation: Lists in Python can store items of different types.
🔹 9. Modifying Individual Elements
Program:mixed[0] = mixed[0] + " items"mixed[1] = mixed[1] + 1mixed[2] = mixed[2] + 0.05mixedAnswer: ['data items', 6, 100.14999999999999, 8287398L]
Explanation: List elements are mutable and can be reassigned individually.
🔹 10. Nested Lists
Program:nested = [fruits, vegetables]nestedAnswer: [['apple', 'mango', 'orange', 'banana', 'pear'], ['potato', 'carrot', 'onion', 'beans', 'radish']]
Explanation: Lists can contain other lists. This is useful for creating matrix-like data structures.
📢 If you found this post helpful, don’t forget to share it with your fellow learners, follow for more Python tips, and drop a comment below with your thoughts or questions! 🐍💬

Comments
Post a Comment