Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Get first index values in tuple of strings in Python
We have a tuple of strings. We are required to create a list of elements which are the first character of these strings in the tuple.
With index
We design a for loop to take each element and extract the first character by applying the index condition as 0. Then the list function converts it to a list.
Example
tupA = ('Mon', 'Tue', 'Wed', 'Fri')
# Given tuple
print("Given list : \n" ,tupA)
# using index with for loop
res = list(sub[0] for sub in tupA)
# printing result
print("First index charaters:\n",res)
Output
Running the above code gives us the following result −
Given list :
('Mon', 'Tue', 'Wed', 'Fri')
First index charaters:
['M', 'T', 'W', 'F']
With next and zip
We apply zip to the tuple and then apply next to get the first character of each element.
Example
tupA = ('Mon', 'Tue', 'Wed', 'Fri')
# Given tuple
print("Given list : \n" ,tupA)
# using next and zip
res = list(next(zip(*tupA)))
# printing result
print("First index charaters:\n",res)
Output
Running the above code gives us the following result −
Given list :
('Mon', 'Tue', 'Wed', 'Fri')
First index charaters:
['M', 'T', 'W', 'F'] Advertisements
