The Wayback Machine - http://web.archive.org/web/20241004182643/https://www.geeksforgeeks.org/python-set-3-strings-lists-tuples-iterations/
Open In App

Python | Set 3 (Strings, Lists, Tuples, Iterations)

Last Updated : 01 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the previous article, we read about the basics of Python. Now, we continue with some more python concepts.

Strings in Python: 

A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a part of a string, they define only starting and ending of the string.  Strings are immutable, i.e., they cannot be changed. Each element of the string can be accessed using indexing or slicing operations.

Python




# Assigning string to a variable
a = 'This is a string'
print (a)
b = "This is a string"
print (b)
c= '''This is a string'''
print (c)


Output:

This is a string
This is a string
This is a string

Lists in Python:

Lists are one of the most powerful data structures in python. Lists are sequenced data types.  In Python, an empty list is created using list() function. They are just like the arrays declared in other languages. But the most powerful thing is that list need not be always homogeneous. A single list can contain strings, integers, as well as other objects. Lists can also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared. The elements of list can be accessed using indexing and slicing operations.

Python




# Declaring a list
L = [1, "a" , "string" , 1+2]
print L
#Adding an element in the list
L.append(6)   
print L
#Deleting last element from a list
L.pop()
print (L)
#Displaying Second element of the list
print (L[1])


The output is:  

[1, 'a', 'string', 3]
[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3]
a

Tuples in Python: A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that tuples cannot be changed once declared. Tuples are usually faster than lists.

Python




tup = (1, "a", "string", 1+2)
print(tup)
print(tup[1])


The output is : 

(1, 'a', 'string', 3)
a

Iterations in Python: Iterations or looping can be performed in python by ‘for’ and ‘while’ loops. Apart from iterating upon a particular condition, we can also iterate on strings, lists, and tuples.

Example 1: Iteration by while loop for a condition

Python




i = 1
while (i < 10):
    print(i)
    i += 1


The output is: 

1
2
3
4
5
6
7
8
9 

Example 2: Iteration by for loop on the string

Python




s = "Hello World"
for i in s:
    print(i)


The output is: 

H
e
l
l
o
 
W
o
r
l
d

Example 3: Iteration by for loop on list

Python




L = [1, 4, 5, 7, 8, 9]
for i in L:
    print(i)


The output is: 

1
4
5
7
8
9

Example 4: Iteration by for loop for range

Python




for i in range(0, 10):
    print(i)


The output is: 

0
1
2
3
4
5
6
7
8
9 


Previous Article
Next Article

Similar Reads

Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Output of python program | Set 12(Lists and Tuples)
Prerequisite: List and Tuples Note: Output of all these programs is tested on Python3 1) What is the output of the following program? C/C++ Code L1 = [] L1.append([1, [2, 3], 4]) L1.extend([7, 8, 9]) print(L1[0][1][1] + L1[2]) a) Type Error: can only concatenate list (not "int") to list b) 12 c) 11 d) 38 Ans: (c) Explanation: In the print(), indexi
3 min read
Using Iterations in Python Effectively
Prerequisite: Iterators in Python Following are different ways to use iterators. C-style approach: This approach requires prior knowledge of a total number of iterations. Python Code # A C-style way of accessing list elements cars = ["Aston", "Audi", "McLaren"] i = 0 while (i < len(cars)): print cars[i] i += 1 C/C++
6 min read
Minimize total cost without repeating same task in two consecutive iterations
Given an array arr[][] of size M X N where M represents the number of tasks and N represents number of iteration. An entry in the array arr[i][j] represents the cost to perform task j at the ith iteration. Given that the same task j cannot be computed in two consecutive iterations, the task is to compute the minimum cost to perform exactly one task
14 min read
Convert Lists to Comma-Separated Strings in Python
Making a comma-separated string from a list of strings consists of combining the elements of the list into a single string with commas between each element. In this article, we will explore three different approaches to make a comma-separated string from a list of strings in Python. Make Comma-Separated String from List of Strings in PythonBelow ar
2 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Make Scatter Plot From Set of Points in Python Tuples
Now we'll look at an example that shows how to use scatter and how scatter values can be passed to a function as a tuple argument. Assume your function takes four and five arguments each argument will be passed as a separate single data point or value to plot the scatter chart. Let's see the implementation of it in Python. What is Scatter in Python
3 min read
Output of Python Programs | Set 20 (Tuples)
Prerequisite: Tuples Note: The output of all these programs is tested on Python3 1. What will be the output of the following program? [GFGTABS] Python3 tuple = (1, 2, 3, 4) tuple.append( (5, 6, 7) ) print(len(tuple)) [/GFGTABS]Options: 125Error Output: 4. ErrorExplanation: In this case an exception will be thrown as tuples are immutable and don’t h
2 min read
Tuples in Python
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable. Creating Python TuplesThere are various ways by which you can create a tuple i
6 min read
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] E
3 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Remove empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Filter dictionary of tuples by condition
Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using items
3 min read
Python | Unzip a list of tuples
The zipping technique, that is assigning a key value or pairing from two different lists has been covered in many articles before, sometimes we have a specific utility to perform the reverse task. This task can be achieved by various methods. Let's discuss some of the methods to unzip a list of tuples. Method #1: Using List comprehension Using list
5 min read
Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Python | Linear search on list or tuples
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is Start from the leftmost element of the list and one by one compare x with each element of the list.If x matches with an element, return True.If x doesn’t match with any of the elements, return False. Example #1: Linear Search o
2 min read
Python | Position Summation in List of Tuples
Sometimes the data that we receive is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the sum of each index of tuple for cumulation. Let's discuss certain ways in which this can be performed. Method #1: Using list comprehension This is the most naive method to perform this par
7 min read
Python | Get sum of tuples having same first value
Given a list of tuples, the task is to sum the tuples having the same first value. Examples: Input: [(1, 13), (2, 190), (3, 82), (1, 12)] Output: [(1, 25), (2, 190), (3, 82)]Input: [(1, 13), (1, 190), (3, 25), (1, 12)] Output: [(1, 215), (3, 25)] Let us discuss the different ways we can do this task. Method #1: Using map() C/C++ Code # Python code
6 min read
Python | Preceding element tuples in list
Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the preceding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let's discuss a way in which this task can be performed. Method #1: Using for loop C/C++ Code # Python3 c
5 min read
Python | Convert Numpy Arrays to Tuples
Given a numpy array, write a program to convert numpy array into tuples. Examples - Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]]) Output: ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1)) Input: ([['manjeet', 'akshat'], ['nikhil', 'akash']]) Output: (('manjeet', 'akshat'), ('nikhil', 'akash')) Method #1: Using tuple and map Step-by-step approach : Import the NumPy
2 min read
How we can iterate through list of tuples in Python
In this article, we will discuss different ways to iterate the list of tuples in Python. It can be done in these ways: Using Loop.Using enumerate().Method 1: Using Loop Here we are going to form a list of tuples using for loop. C/C++ Code # create a list of tuples with student # details name = [('sravan',7058,98.45), ('ojaswi',7059,90.67), ('bobby'
2 min read
Python Memory Consumption: Dictionary VS List of Tuples
In this article, we are going to see memory consumption in dictionaries and a list of tuples. Memory Consumption by dict vs list of tuples Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory
4 min read
Python - Dict of tuples to JSON
In this article, we will discuss how to convert a dictionary of tuples to JSON. Method 1: Using json.dumps() This will convert dictionary of tuples to json Syntax: json.dumps(dictionary, indent) Parameters: dictionary is the input dictionary.indent specify the number of units of indentation Example: Python dict of tuples to json conversion C/C++ Co
2 min read
Python - Create a List of Tuples
List and tuples both are data structures in Python, with some differences. Lists are mutable data structures whereas tuples are immutable (can not be changed after creating it). We can make a list that contains tuples as elements. This practice is useful for data structuring, memory efficiency, and data security as tuples are immutable. In this art
4 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different methods, each offering its own advantages in differen
3 min read
Python Tuples
Python Tuple is a collection of Python Programming objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers.  Values of a tuple are syntactically separated by 'commas'. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. Th
9 min read
Creating a Pandas DataFrame using Dict of Tuples in Python
Working with Python dictionaries containing tuples is a common scenario, especially when dealing with heterogeneous data. Transforming this data into a Pandas DataFrame allows for efficient manipulation and analysis. In this article, we will see how we can convert a dictionary with a tuple into a DataFrame in Python. Convert Dictionary with Tuple i
2 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = "10" # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Output of Python program | Set 6 (Lists)
Prerequisite - Lists in Python Predict the output of the following Python programs. These question set will make you conversant with List Concepts in Python programming language. Program 1 Python Code list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print &quot;list1[0]: &quot;, list1[0] #statement 1 print &qu
3 min read
Practice Tags :