Showing posts with label lists. Show all posts
Showing posts with label lists. Show all posts

Monday, 29 January 2024

Convert a list to tuple in Python

Tuples in Python are similar to lists in that they are ordered collections of items, but they differ in being immutable, meaning once created, their contents cannot be changed.

Following are the various approaches to convert a list to a tuple.

 

Approach 1: Using tuple() function.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = tuple(primes_list)

In the above Python snippet, a list of prime numbers is first created and then converted into a tuple. Initially, primes_list is defined as a list containing the first five prime numbers: 2, 3, 5, 7, and 11. Lists in Python are mutable, ordered collections of items, which in this case are integer values representing prime numbers. Following this, primes_tuple is created by converting primes_list into a tuple using the tuple() function.

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = tuple(primes_list)
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>

Approach 2: Using unpacking (*) operator.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = (*primes_list,)

In the above Python code, a list of prime numbers is initially defined, and then this list is converted into a tuple using the unpacking operator *.

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = (*primes_list,)
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>

Approach 3: Using for loop.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = ()

for item in primes_list:
   primes_tuple += (item,)

Above snippet demonstrates a process for converting a list of prime numbers into a tuple through iteration. The code begins by defining primes_list, a list containing the first five prime numbers: 2, 3, 5, 7, and 11. The conversion from the list to the tuple is achieved using a for loop. The loop iterates over each item in primes_list. Within the loop, the current item is added to primes_tuple using the += operator, which in the context of a tuple, creates a new tuple by concatenating the existing primes_tuple with a new tuple containing the current item, (item,).

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = ()
>>> 
>>> for item in primes_list:
...    primes_tuple += (item,)
... 
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>


 

Previous                                                 Next                                                 Home

Sunday, 28 January 2024

Convert tuple to a list in Python

Approach 1: Using list() function

Using list() function, we can convert a tuple to list.

 

Example

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = list(emp)

 

emp_as_list = list(emp)

This line converts the emp tuple into a list. The list() function is a built-in Python function that takes an iterable (like a tuple, a set, or a dictionary) and returns a new list with the same elements. In this case, emp_as_list becomes a list containing the same elements as the emp tuple: [1, 'Krishna', 'Bangalore', 34].

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = list(emp)
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

Approach 2: Using list comprehensions.

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = [item for item in emp]

emp_as_list = [item for item in emp]

This line uses a list comprehension to convert the emp tuple into a list. List comprehensions are a concise way to create lists in Python. The syntax [item for item in emp] means "create a list consisting of each item taken from the emp tuple." This process iterates over each element in the emp tuple and places each element into a new list. The result is that emp_as_list becomes a list containing the same elements as the emp tuple: [1, 'Krishna', 'Bangalore', 34].

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = [item for item in emp]
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

Approach 3: using for loop

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = []
for item in emp:
  emp_as_list.append(item)

 

emp_as_list = []

This line initializes an empty list named emp_as_list. In Python, lists are mutable and ordered collections of items. This list is intended to store the elements of the emp tuple.

 

for item in emp:

Above snippet iterates over each element in the emp tuple.

 

emp_as_list.append(item):

Inside the for loop, each item from the tuple emp is appended to the list emp_as_list using the append() method. This method adds the item to the end of the list.

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = []
>>> for item in emp:
...   emp_as_list.append(item)
... 
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

 

Approach 4: Using unpacking (*) operator

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = [*emp]

emp_as_list = [*emp]

This line converts the emp tuple into a list. The * operator, known as the unpacking operator in Python, is used here to unpack the elements of the tuple emp. When used within the square brackets [], it effectively takes all elements from the tuple and places them into a new list.

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = [*emp]
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

Sometimes, you might want to apply some transformations on the tuple elements while adding them to a list, you can combine list with map function to achieve this.

 

hobbies_as_list = list(map(lambda x : x.upper(), hobbies))

Above statement convert each hooby in the tuple to uppercase while adding to the list.

 

lambda x : x.upper(): This is a lambda function, an anonymous (nameless) function in Python. x is the input parameter, and x.upper() is the operation performed on this parameter. x.upper() converts the string x to uppercase.

 

map(lambda x : x.upper(), hobbies): The map function applies the lambda function to each element of the hobbies tuple. The map function takes two arguments: a function and an iterable (in this case, the hobbies tuple). It applies the given function (the lambda function) to each item of the iterable and returns a map object.

 

list(...): The map object returned by the map function is then converted into a list using the list() constructor. This is necessary because map returns a map object, not a list, and the goal here is to have a list of the modified elements.

>>> hobbies = ('football', 'cricket', 'singing', 'cooking')
>>> hobbies_as_list = list(map(lambda x : x.upper(), hobbies))
>>> 
>>> hobbies
('football', 'cricket', 'singing', 'cooking')
>>> type(hobbies)
<class 'tuple'>
>>> 
>>> 
>>> hobbies_as_list
['FOOTBALL', 'CRICKET', 'SINGING', 'COOKING']
>>> type(hobbies_as_list)
<class 'list'>

 

Previous                                                 Next                                                 Home

Wednesday, 24 January 2024

Pandas: Convert all the column values to upper case

'upper()' method converts the Strings in given column to upper case and return a new series with the updated data.

Example

df['Name'] = df['Name'].str.upper()

 

As you see above snippet, we are using 'str' accessor to perform the string operations

 

Find the below working application.

 

upper.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [67, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df['Name'] = df['Name'].str.upper()
df['City'] = df['City'].str.upper()
df['Gender'] = df['Gender'].str.upper()

print('\nDataFrame after converting the columns data to upper case \n', df)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      67
1     Sailu   35  Hyderabad  Female      43
2      Joel  234  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

DataFrame after converting the columns data to upper case 
        Name  Age       City  Gender  Rating
0   KRISHNA   34  BANGALORE    MALE      67
1     SAILU   35  HYDERABAD  FEMALE      43
2      JOEL  234  HYDERABAD    MALE      67
3     CHAMU   35    CHENNAI  FEMALE     100
4  JITENDRA   52  BANGALORE    MALE      41
5   KRISHNA   34    CHENNAI    MALE      89


 

Previous                                                 Next                                                 Home

Pandas: Convert all the column values to lower case

'lower()' method converts the Strings in given column to lowercase and return a new series with the updated data.

Example

df['Name'] = df['Name'].str.lower()

As you see above snippet, we are using 'str' accessor to perform the string operations

 

Find the below working application.

 

lower.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [67, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df['Name'] = df['Name'].str.lower()
df['City'] = df['City'].str.lower()
df['Gender'] = df['Gender'].str.lower()

print('\nDataFrame after lowering the string columns \n', df)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      67
1     Sailu   35  Hyderabad  Female      43
2      Joel  234  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

DataFrame after lowering the string columns 
        Name  Age       City  Gender  Rating
0   krishna   34  bangalore    male      67
1     sailu   35  hyderabad  female      43
2      joel  234  hyderabad    male      67
3     chamu   35    chennai  female     100
4  jitendra   52  bangalore    male      41
5   krishna   34    chennai    male      89



Previous                                                 Next                                                 Home

Iterate over the elements of a list using for loop in Python

Approach 1: Iterate over the list, element by element.

 iterate_ele_by_ele.py

primes = [2, 3, 5, 7, 11]

for ele in primes:
    print(ele)

Output

2
3
5
7
11

Above snippet is a simple example of a for loop used to iterate over a list and print each element.

 

primes = [2, 3, 5, 7, 11]

This line initializes a list named primes containing five elements: the prime numbers 2, 3, 5, 7, and 11.

 

for ele in primes:

This line starts a for loop. The loop will iterate over each element in the primes list. In each iteration, the variable ele will be assigned to the current element of the list.

 

print(ele)

This line is the body of the for loop and is executed for each iteration of the loop. It prints the current value of ele, which is the element from the primes list being accessed in that iteration.

 

When this snippet is run, it sequentially accesses each element in the primes list, assigns it to ele, and then prints it.

 

Approach 2: Iterate over a list using index.

 

iterate_by_index.py

primes = [2, 3, 5, 7, 11]

for index in range(len(primes)):
    print(f'{index}. {primes[index]}')

Output

0. 2
1. 3
2. 5
3. 7
4. 11

Above snippet uses a for loop to iterate over the indices of a list and print each index along with its corresponding element.

 

for index in range(len(primes)):

This line initiates a for loop with a few key components:

 

a.   len(primes): This function call returns the length of the primes list, which is 5.

b.   range(len(primes)): range(5) generates a sequence of numbers from 0 to 4 (since range in Python is exclusive of the end value). These numbers will be used as indices to access elements in the primes list.

c.    for index in: This part sets up the for loop, where index will successively take on the values from the range(len(primes)) sequence – 0, 1, 2, 3, and 4 in each iteration.

 

print(f'{index}. {primes[index]}')

Inside the loop, this print statement is executed for each iteration. It uses an f-string (formatted string literal) to create a string that includes:

 

a.   index: The current index in the loop.

b.   primes[index]: The element in the primes list at the current index.

 

As a result, when this snippet is executed, it will print each index and its corresponding value from the primes list in the format "index. value".

 

Approach 3: Using enumerate method.

 

iterate_using_enumerate.py

primes = [2, 3, 5, 7, 11]

for index, prime_number in enumerate(primes):
    print(f"{index}. {prime_number}")

Output

0. 2
1. 3
2. 5
3. 7
4. 11

Above snippet uses a for loop combined with the enumerate function to iterate over a list, providing both the index and the value of each element in the list.

 

for index, prime_number in enumerate(primes):

This line starts a for loop with the enumerate function applied to the primes list.

 

a.   enumerate(primes): The enumerate function adds a counter to an iterable (in this case, the primes list) and returns it as an enumerate object. This object produces pairs that contain a count (from start, which defaults to 0) and the values obtained from iterating over the iterable.

b.   index, prime_number: In each iteration, enumerate returns a tuple (index, prime_number), where index is the current index of the element in the list, and prime_number is the actual element at that position in the primes list.


Previous                                                 Next                                                 Home