0% found this document useful (0 votes)
19 views11 pages

Python Lists, Tuples, and Strings Guide

The document provides an overview of lists, tuples, and strings in Python, including their creation, manipulation, and various operations such as appending, inserting, and sorting. It includes examples of how to access elements, search for values, and perform string operations like concatenation and slicing. Additionally, it discusses membership and relational operators in the context of strings.

Uploaded by

muhsinmuhammadb
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views11 pages

Python Lists, Tuples, and Strings Guide

The document provides an overview of lists, tuples, and strings in Python, including their creation, manipulation, and various operations such as appending, inserting, and sorting. It includes examples of how to access elements, search for values, and perform string operations like concatenation and slicing. Additionally, it discusses membership and relational operators in the context of strings.

Uploaded by

muhsinmuhammadb
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

list_tuple_string

January 2, 2025

1 Lists
[23]: list1 = []
list2 = [56]
friends = ["Saisha", "Advika", "Arshia"]
marks = [92, 91, 89, 95, 93, 45, 91, 48]
students = [21, "Gunjan" ,94.5 , 34, "Rohit", 91.3]
section = ["A", 25, "English", ["B", 34], ["c", 37], 56.7]
l1 = [10] * 5
aplha = list("hello")
# l1 = list(input("Enter numbers:"))

[6]: l1 = ['P', 'Y', 'T', 'H', 'O', 'N']


print(l1[0])
print(l1[3])
print(l1[-3])
print(l1[-1])
print(l1)
print(l1[0], l1[4])

P
H
H
N
['P', 'Y', 'T', 'H', 'O', 'N']
P O

[3]: word = ['E', 'D', 'U', 'C', 'A', 'T', 'I', 'O', 'N']
print(word[:1:-2])
print(word[-1:])
print(word[:-1])

['N', 'I', 'A', 'U']


['N']
['E', 'D', 'U', 'C', 'A', 'T', 'I', 'O']

[25]: word[4:-2:-2]

[25]: []

1
2 List Operations
2.1 append()
[10]: fruits = ["apple", "banana", "cherries"]
[Link]("melon")
print(fruits)

['apple', 'banana', 'cherries', 'melon']

[11]: cars = ["Maruthi", "Ford"]


[Link]("Honda")
[Link]("Hyundai")
print(cars)

['Maruthi', 'Ford', 'Honda', 'Hyundai']

[12]: friends = []
for i in range(5):
nm = input("Enter Friends Name:")
[Link](nm)
print(friends)

Enter Friends Name:naimu


Enter Friends Name:heb
Enter Friends Name:he
Enter Friends Name:hbt
Enter Friends Name:bhwr
['naimu', 'heb', 'he', 'hbt', 'bhwr']

[13]: pets = ['cat', 'dog', 'rabbit']


wild = ['tiger', 'lion']
[Link](wild)
print(pets)

['cat', 'dog', 'rabbit', ['tiger', 'lion']]

2.2 insert()
[17]: l = [10, 20, 30]

[18]: [Link](1,40)
print(l)

[10, 40, 20, 30]

[19]: [Link](0, "abc")


print(l)

['abc', 10, 40, 20, 30]

2
[20]: a = "xyz"
[Link](3, a)
print(l)

['abc', 10, 40, 'xyz', 20, 30]

[21]: [Link](5, ["a", "b"])


print(l)

['abc', 10, 40, 'xyz', 20, ['a', 'b'], 30]

2.3 extend()
[23]: n = [1,2,3,4]
m = [ 5 ];
[Link](m)
print(n)

[1, 2, 3, 4, 5]

[24]: pets = ['cat', 'dog', 'rabbit',]


wild = ['tiger', 'lion']
[Link](wild)
print(pets)

['cat', 'dog', 'rabbit', 'tiger', 'lion']

2.4 sort()
[2]: city = ["Delhi", "Mumbai", "Kolkata", "Chennai"]
[Link]()
print(city)

['Chennai', 'Delhi', 'Kolkata', 'Mumbai']

[5]: [Link](reverse=True)
print(city)

['Mumbai', 'Kolkata', 'Delhi', 'Chennai']

2.5 Searching a value in a list


[17]: # Searching a specific value and displaying its number of occurences in a list
A = [10, 23, 45, 10, 12, 45, 10, 56]
s = int(input('Enter the value you want to search:'))
count = 0
for i in A:
if i == s:
count+=1
print(s," occurs ", count, " times")

3
Enter the value you want to search:87
87 occurs 0 times

[38]: # Input a value and search whether it exists in a list or not. if it exists␣
↪then dispaly its index number.

flowers = ["Rose", "Lily", "Lotus", "Sunflower"]


s = input("Input a name of a flower")
for i in range(len(flowers)):
if s == flowers[i]:
print(s, "found at index number", i)
break
else:
print("Sorry, Not found")

Input a name of a flowerSunflower


Sunflower found at index number 3

3 Tuples
[15]: tup1 = ('sst', 'chemistry', 2010, 2022)
tup2 = (1, 2, 3, 4, 5)
tup3 = (1, 2.5, 3.6, 4, 5)
tup4 = (3, "Orange", 45.5)
tup5 = (162, [7, "orange", 15.5], (2, "Orange Education", 70.5))

[4]: tup = tuple('orange')


tup

[4]: ('o', 'r', 'a', 'n', 'g', 'e')

3.1 Accessing Tuples


[6]: print(tup1[1])
print(tup2[3])

chemistry
4

3.2 Deleting a Tuple


[16]: tup5

[16]: (162, [7, 'orange', 15.5], (2, 'Orange Education', 70.5))

[17]: del tup5

[19]: tup = (2,5,7,8,2,1)


print([Link](2))

4
print([Link](7))

2
2

[20]: lst1 = list(tup)


lst1[-1] = 11
tup = tuple(lst1)
print("Modified tuple:", tup)

Modified tuple: (2, 5, 7, 8, 2, 11)

[21]: print(type(tup))
print(type(lst1))

<class 'tuple'>
<class 'list'>

4 Strings
[1]: s1 = 'Hello World'
s2 = "Good Morning"

[3]: print(s1)
print(s2)

Hello World
Good Morning

[43]: s3 = """python is an intresting


programming language"""

[45]: print(s3)

python is an intresting
programming language

[47]: s4 = '''It is a free annd open source.


Happy Learning!'''

[49]: print(s4)

It is a free annd open source.


Happy Learning!

[51]: s5 = """python is an intresting \


programming language"""

[53]: print(s5)

5
python is an intresting programming language

[55]: nm = input('Enter your name: ')


print('Hello', nm, 'Happy Learning!')

Enter your name: Ram


Hello Ram Happy Learning!

4.1 Accessing elements of the String


[2]: s1 = 'PYTHON'

print(s1[0])
print(s1[3])
print(s1[-3])
print(s1[-1])
print(s1)
print(s1[0], s1[4])
print(s1[1+4])
# print(s1[10])
# print(s1[5.5])

P
H
H
N
PYTHON
P O
N

4.2 Traversing a String


[57]: txt = "WONDERFUL"
for indx in txt:
print(indx)

W
O
N
D
E
R
F
U
L

[33]: txt = "WONDERFUL"


for indx in txt:

6
print(indx, end="*")

W*O*N*D*E*R*F*U*L*

[6]: txt = "WONDERFUL"


for i in range(len(txt)):
print(txt[i], end="!")

W!O!N!D!E!R!F!U!L!

[7]: txt = "NATURE"


for i in range(len(txt)):
print(i, end="@")

0@1@2@3@4@5@

4.3 Multiline Strings


[9]: multiline_str = """
This is my favorite book.
It is very intresting to read.
"""
print(multiline_str)

This is my favorite book.


It is very intresting to read.

[17]: multiline_str = """


This is my favorite book.\
It is very intresting to read.\
"""
print(multiline_str)

This is my favorite [Link] is very intresting to read.

4.4 Concatenating Strings


[24]: str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)

Hello World

[30]: str_list = ["Hello", "World"]


concatenated_str = " ".join(str_list)
print(concatenated_str)

7
Hello World

[59]: str_list = ["Hello", "World"]


concatenated_str = "$".join(str_list)
print(concatenated_str)

Hello$World

4.5 String Operations


4.5.1 ‘+’ and ’*’ operator

[33]: S = "LIFE"
T = "IS"
U = "BEAUTIFUL"
S + " " + T +" " + U

[33]: 'LIFE IS BEAUTIFUL'

[34]: 'hi' * 3

[34]: 'hihihi'

[35]: 3 * 'hello' * 2

[35]: 'hellohellohellohellohellohello'

4.6 Membership Operators


[37]: # in operator
'el' in 'Delhi'

[37]: True

[38]: # not in operator


'is' not in 'Life is beautiful'

[38]: False

4.7 Relational Operators


[39]: 'a' == 'A'

[39]: False

[40]: 'abc' > 'abC'

[40]: True

8
[43]: 'hi' != "Hi"

[43]: True

[44]: # To print the ASCII values


ord('a')
ord('8')

[44]: 56

4.8 String Slicing


“ “ ” For forward (positive) indexing of a string s, default values are start_index = 0 end_index =
len(s) ——>
For backward (negative) indexing of a string s, default values are
start_index = -1
end_index = -len(s) - 1
<-------
““”

[17]: txt = "PROGRAMMING IS AMAZING"


txt[::]

[17]: 'PROGRAMMING IS AMAZING'

[19]: print(len(txt))

22

[25]: txt[22::]

[25]: ''

[27]: print(txt[22::])

[65]: print(txt[::1])
print(txt[::-1])
print(txt[:7:1])
print(txt[4::1])
print(txt[3:7])
print(txt[15:])
print(txt[-1:-10:-1])

PROGRAMMING IS AMAZING
GNIZAMA SI GNIMMARGORP
PROGRAM
RAMMING IS AMAZING

9
GRAM
AMAZING
GNIZAMA S

[67]: s = "EDUCATION"
print(s[-9:-6])
print(s[3:-3])
print(s[7:-5:-1])
print(s[:1:-2])

EDU
CAT
OIT
NIAU

[9]: string = 'PROGRAMMING IN PYTHON'

[39]: # String Functions


print(len(string))
print([Link]())
print([Link]())
print([Link]('PRO'))
print([Link]('PYTHON'))
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]('IN'))
print([Link]('in'))
print([Link]('IN',10,15))
print([Link]('M','_'))
print([Link]('O'))
print([Link]('O', 1, 15))

21
Programming in python
Programming In Python
True
True
False
False
False
False
programming in python
PROGRAMMING IN PYTHON

10
False
True
8
-1
12
PROGRA__ING IN PYTHON
2
1

[22]: city = 'DELHI'


s = '@'
[Link](city)

[22]: 'D@E@L@H@I'

[26]: a= ["orange"]
b = ["education"]
c = a + b
print(c)

['orange', 'education']

[ ]:

11

Common questions

Powered by AI

The append operation adds its argument as a single element to the end of a list, whereas the extend operation iterates over its argument adding each element to the list. This means that append can create nested lists if a list is appended, while extend will only add elements, not other lists. For example, appending a list to another list results in a nested list structure , whereas using extend would integrate the elements of the second list into the first .

The choice between tuples and lists hinges on requirements for mutability and performance. Tuples should be considered when immutability is essential, such as when using them as keys in dictionaries or when defining fixed collections of mixed data types. They provide assurance that data won't change unexpectedly and can be more performance-efficient due to their immutability . Lists are preferred when data modification is necessary, as they support dynamic operations like appending, extending, and slicing with ease. Both structures offer unique facilities that meet different programmatic needs, balancing flexibility with data integrity.

Converting tuples to lists allows for modification of the sequence, which is not possible directly on tuples due to their immutability. This conversion process is significant because it provides a workaround for modifying immutable data structures for data manipulation purposes. After modifications are made on the list, it can be converted back to a tuple for scenarios where immutability is required, such as maintaining data integrity . This conversion is essential for allowing modifications while leveraging the benefits of both mutable and immutable data structures in Python.

Relational operators play a crucial role in comparing strings based on lexicographical order, often reflecting dictionary order. This comparison influences sorting mechanisms where strings are sorted according to Unicode values character by character. For example, 'abc' > 'abC' results in True, since the lowercase 'c' has a higher Unicode value than 'C' . This understanding is fundamental for accurately implementing sorting algorithms that rely on string comparisons, affecting how data is organized and retrieved based on textual criteria.

Membership operators like 'in' and 'not in' simplify the implementation of conditional logic by allowing programmers to check the presence or absence of substrings within larger strings efficiently. This aids in operations such as filtering, validation, and decision-making, where actions depend on whether certain patterns or characters exist within a text. For example, checking whether 'el' is in 'Delhi' returns True, which can be instrumental for dynamic validations and data processing within a codebase . This enhances readability and reduces errors in condition checks.

Safe indexing prevents accessing characters beyond the valid range of a string, which would result in an IndexError. This is crucial in string traversal to ensure each index accessed contains a valid character. Using constructs like length checks within loops helps avoid surpassing the string boundary, thereby preventing runtime errors that can disrupt program execution. For instance, ensuring indices are evaluated against the string length before use is a direct mechanism to maintain robust and error-free code .

In tuples, accessing an element using a wrong index will raise an IndexError, since tuples are immutable and do not support index modification. Unlike lists, where an element can be replaced by assigning a new value to an existing index, tuples do not allow assignment to indexes . Additionally, the strict requirement of accurate indexing in tuples reflects their immutability, contrasting with the more flexible list that can have elements dynamically replaced or modified without raising an error.

Using a loop to traverse a list is explicit, showing step-by-step each element's access and processing, making the process transparent but potentially verbose, especially when performing simple transformations or filtering. In contrast, list comprehension provides a concise and efficient way to create lists by expressing a construction rule in a single line of code. This not only makes the code more readable and compact but often runs faster as it is optimized internally by Python . The declarative nature of list comprehension also aids in focusing on what should be done, rather than how.

The capitalize method converts the first character of a string to uppercase, which is useful for standardizing sentence case formatting, making it suitable for titles and single-line headings. The title method capitalizes the first character of each word, ensuring consistent formatting for multi-word titles or names, which is crucial in generating readable and professionally-standardized documents or user interfaces. These methods facilitate aesthetic uniformity and readability, contributing to a seamless user experience . They play a pivotal role in applications that handle arbitrary text inputs needing consistency.

Slicing operations on strings offer the flexibility to access and manipulate substrings efficiently, including reversing the order of characters. This capability is crucial in practical applications such as generating palindromes, reversing words for cryptographic functions, or formatting string outputs in reverse for aesthetic or functional purposes. The slicing mechanism allows programmers to easily span and rearrange sequences for structure transformations without requiring additional data structures . The versatility of slicing, especially in reverse, can optimize text processing tasks considerably.

You might also like