Python Lists (With Examples)

 PYTHON LISTS:

In Python, a list is a built-in data structure that allows you to store and manage a collection of items, which can be of any data type, including other lists. Lists are ordered, mutable, and can contain duplicate elements. Lists are defined using square brackets [], and individual elements within the list are separated by commas.

Python Lists (With Examples)| diplomawaale.blogspot.com
Python Lists



LIST DECLARATION:

                                          # Creating a list with some initial elements
                                          fruits = ['apple', 'banana', 'orange']

                                           # Sorting the list in alphabetical order
                                           fruits.sort()

                                           # Reversing the order of elements
                                           fruits.reverse()

                                            # Creating an empty list
                                            empty_list = []

                                            # Creating a list with repeat elements
                                            repeated = [0] * 5

                                            # Using list comprehension to create a list of squares
                                            squares = [x ** 2 for x in range(1, 6)]

                                            # Creating a nested list
                                            matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

                                            # Creating a list from an iterable using the list() constructor
                                            numbers_list = list(range(1, 6))

                                            # Printing the results
                                            print("Fruits:", fruits)
                                            print("Popped Fruit:", popped_fruit)
                                            print("Empty List:", empty_list)
                                            print("Repeated List:", repeated)
                                            print("Squares:", squares)
                                            print("Matrix:", matrix)
                                            print("Numbers List:", numbers_list)


CHARACTERISTICS OF PYTHON: 

  1. Ordered: Lists maintain the order of elements as they are added, allowing predictable access by index.
  2. Mutable: Lists can be changed after creation, enabling the addition, modification, or removal of elements.
  3. Heterogeneous Elements: Lists can hold diverse data types, accommodating numbers, strings, booleans, and more within a single list.
  4. Variable Length: Lists can dynamically grow or shrink in size, accommodating varying numbers of elements.
  5. Indexing and Slicing: Elements in a list are accessed by index, with the option to extract sublists using slicing.
  6. Iterability: Lists are iterable, allowing you to loop through their elements using iteration constructs like for loops.


INDEXING AND SLICING:

  1. Indexing:
  • Indexing allows you to access individual elements of a list using their position (index).
  • The index starts from 0 for the first element, and it increments by 1 for each subsequent element.
  • You can also use negative indices to count from the end of the list.

2. Slicing:

  • Slicing allows you to extract a portion (sublist) from a list.
  • The syntax for slicing is a list[start: end], where the start is inclusive and the end is exclusive.
  • If you omit start, slicing starts from the beginning; if you omit end, slicing goes to the end of the list.

EXAMPLE:

                                    # Define a list of fruits
                                    fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']

                                     # Indexing Explanation
                                     # Accessing individual elements using indices
                                     first_fruit = fruits[0]   # Element at index 0: 'apple'
                                     third_fruit = fruits[2]   # Element at index 2: 'orange'
                                     last_fruit = fruits[-1]   # Last element using a negative index: 'kiwi'
                                     second_last_fruit = fruits[-2]  # Second-to-last element using a negative index:                                           'grape'

                                     # Slicing Explanation
                                     # Extracting sublists using slicing
                                     sublist_1 = fruits[1:4]   # Elements from index 1 to 3 (4 is exclusive): ['banana',                                       'orange', 'grape']
                                     sublist_2 = fruits[:3]    # Elements from the beginning to index 2: ['apple',                                                 'banana', 'orange']
                                      sublist_3 = fruits[2:]    # Elements from index 2 to the end: ['orange', 'grape',                                             'kiwi']
                                      sublist_4 = fruits[0:5:2]  # Every second element from index 0 to 4: ['apple',                                              'orange', 'kiwi']

                                       # Length and Last Element Explanation
                                       # Getting the length of the list and accessing the last element
                                       length_of_fruits = len(fruits)  # Length of the list: 5
                                       last_element = fruits[-1]       # Last element using a negative index: 'kiwi'

                                       # Print the results
                                       print("Indexing:")
                                       print("First Fruit:", first_fruit)
                                       print("Third Fruit:", third_fruit)
                                       print("Last Fruit:", last_fruit)
                                       print("Second-to-Last Fruit:", second_last_fruit)

                                       print("\nSlicing:")
                                       print("Sublist 1:", sublist_1)
                                       print("Sublist 2:", sublist_2)
                                       print("Sublist 3:", sublist_3)
                                       print("Sublist 4:", sublist_4)

                                       print("\nLength and Last Element:")
                                       print("Length of Fruits List:", length_of_fruits)
                                       print("Last Element:", last_element)


UPDATING LIST VALUES:

Updating values in a list involves modifying the content of a specific element at a given index. Lists in Python are mutable, so you can change their elements after creation.

EXAMPLE:

Python Lists (With Examples)| diplomawaale.blogspot.com


BUILT-IN FUNCTION:

Sr.No.

Function with Description

1

cmp(list1, list2)

Compares elements of both lists.

2

len(list)

Gives the total length of the list.

3

max(list)

Returns item from the list with max value.

4

min(list)

Returns item from the list with min value.

5

list(seq)

Converts a tuple into list.

 HERE ARE SOME OTHER ADDITIONAL METHOD:

Sr.No.

Methods with Description

1

list.append(obj)

Appends object obj to list

2

list.count(obj)

Returns count of how many times obj occurs in list

3

list.extend(seq)

Appends the contents of seq to list

4

list.index(obj)

Returns the lowest index in list that obj appears

5

list.insert(index, obj)

Inserts object obj into list at offset index

6

list.pop(obj=list[-1])

Removes and returns last object or obj from list

7

list.remove(obj)

Removes object obj from list

8

list.reverse()

Reverses objects of list in place

9

list.sort([func])

Sorts objects of list, use compare func if given

 



Post a Comment

0 Comments