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:

  1. 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.

  2. Modifying Contents:

    • Adding elements: Use append(), insert(), or extend().

      • Example: my_list.append(10)

    • Removing elements: Use remove(), pop(), or del.

      • Example: my_list.pop(2) removes the third item.

    • Updating values directly via index:

      • Example: my_list[0] = 100

  3. 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.

  4. 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] returns 3.

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(), and sum() when appropriate.

  • Iteration: Lists are iterable, allowing them to be looped over with for or comprehensions.

Use Cases:

  1. Storing sequences of data such as names, numbers, or objects.
  2. Implementing stacks, queues, and other custom data structures.
  3. 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')
fruits
Answer: ['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')
fruits
Answer: ['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 + vegetables
eatables
Answer: ['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:
mixed = ['data', 5, 100.1, 8287398L]
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] + 1
mixed[2] = mixed[2] + 0.05
mixed
Answer: ['data items', 6, 100.14999999999999, 8287398L]

Explanation: List elements are mutable and can be reassigned individually.

🔹 10. Nested Lists

Program:

nested = [fruits, vegetables]
nested
Answer: [['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

Popular posts from this blog

Fundamental of python : 1.Python Numbers