Monday, 11 December 2023

Python Collection -- LISTS


# Converting String to List and List to records.

>>> pkeys="ECD,ENAME"

>>> pklist=pkeys.split(",")

 >>> for k in range(0,len(pklist)):

...     print('SRC.'+ pklist[k])

...

SRC.ECD

SRC.ENAME


# Converting TUPLE to List

>>> my_tuple = ('item_1', 'item_2', 'item_3', ...)

>>> my_list = []

>>> for i in my_tuple:

...     my_list.append(i)

...

>>> print(my_list)

['item_1', 'item_2', 'item_3', Ellipsis]


# Converting Dictionary to List

>>> d = {"name": "python", "version": 3.9}

>>> new_list = []

>>> for key, val in d.items():

...     new_list.append([key, val])

...

>>> print(new_list)

[['name', 'python'], ['version', 3.9]]


# Automating Lists in Python

>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']

>>> for i in range(len(supplies)):

...      print('Index ' + str(i) + ' in supplies is: ' + supplies[i])

...

Index 0 in supplies is: pens

Index 1 in supplies is: staplers

Index 2 in supplies is: flamethrowers

Index 3 in supplies is: binders


# Iterating TUPLES inside a LIST

>>> name = [('sravan',7058,98.45),

... ('ojaswi',7059,90.67),

... ('bobby',7060,78.90),

... ('rohith',7081,67.89),

... ('gnanesh',7084,98.01)]

>>> # iterate using for loop

>>> for x in name:

... # iterate in each tuple element

...      for y in x:

...          print(y)

...

sravan

7058

98.45

ojaswi

7059

90.67

bobby

7060

78.9

rohith

7081

67.89

gnanesh

7084

98.01

# Finding the largest number in the List

my_list=[3,4,5,7,8,88,99,33,56,46]

largest = 0

for i in range(0,len(my_list)):

    if my_list[i] > largest:

       largest = my_list[i]


print(largest)

99

# Printing ID for an Object

Python id() FunctionThe id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object's memory address, and will be different for each time you run the program. shopping_list = ["milk",                 "pasta",                 "eggs",                 "spam",                 "bread",                 "rice"                 ]another_list = shopping_listprint(id(shopping_list))print(id(another_list))################################################################################### Converting Dictionary to List of Tuples # Converting Dictionary to List of Tuples >>> my_dict = {'a': 1}>>> items_list = []>>> for key, value in my_dict.items():...     items_list.append((key, value))...>>> print(items_list)[('a', 1)]
# Converting List of tuples to Records.k=[('a', 1)]for i in k:    for y in i:      print(y)a1
################################################################################### Using pop() to remove and return the last elementmy_list = [1, 2, 3, 4, 5]popped_element = my_list.pop()print("Popped element:", popped_element)print("Updated list:", my_list)
# Using remove() to remove a specific elementmy_list = [1, 2, 3, 4, 3, 5]my_list.remove(3)print("Updated list:", my_list)################################################################################### Iterating over List of dictionarieslist_of_dicts = [    {'name': 'Alice', 'age': 25, 'city': 'New York'},    {'name': 'Bob', 'age': 30, 'city': 'San Francisco'},    {'name': 'Charlie', 'age': 22, 'city': 'Los Angeles'}]# Iterating over the list of dictionariesfor my_dict in list_of_dicts:    # Accessing key-value pairs within each dictionary    for key, value in my_dict.items():        print(f"{key}: {value}")    print()  # Print an empty line between dictionaries for clarity##################################################################################Remove duplicate data from the list # Create a list with duplicatesdata = [1, 3, 45, 3, 1, 6, 7, 8, 9]
# Create an empty list to store unique elementsunique_data = []
# Iterate through the original listfor item in data:    # Check if the item is not already present in the unique_data list    if item not in unique_data:        # Add the item to the unique_data list        unique_data.append(item)
# Print the original list and the list without duplicatesprint(f"Original list: {data}")print(f"List without duplicates: {unique_data}")##################################################################################Retrieve the highest value in the List # Create a list with duplicatesdata = [1, 3, 45, 3, 1, 6, 7, 8, 9]
# Initialize a variable to store the highest valuehighest_value = data[0]
# Iterate through the listfor item in data:    # Compare the current item with the highest value    if item > highest_value:        # Update the highest value if the current item is greater        highest_value = item
# Print the highest valueprint(f"Highest value in the list: {highest_value}##################################################################################Flatten the Nested List list1 = [[1, 2, 3],[4, 5, 6]]newlist = []for list2 in list1: for j in list2:      newlist.append(j)print(newlist)##################################################################################





No comments:

Post a Comment

SQL -

 Window Functions -  Window function: pySpark window functions are useful when you want to examine relationships within group of data rather...