Output of Python Program | Set 5 (Lists and Tuples)
×


Output of Python Program | Set 5 (Lists and Tuples)

182

Output of Python Program | Set 5 (Lists and Tuples)

Lists and Tuples are fundamental data structures in Python used to store collections of items. While lists are mutable, allowing modification after creation, tuples are immutable and cannot be changed once defined. Understanding how these data types behave in different scenarios is key to writing effective Python code.

Working with Lists

Lists are ordered collections that can hold elements of different data types. You can add, remove, or change items in a list.

my_list = [10, 20, 30, 40]
my_list[1] = 25
print(my_list)

Output:

[10, 25, 30, 40]

Here, the second element (index 1) of the list is updated from 20 to 25.

Working with Tuples

Tuples are similar to lists but are immutable, meaning their elements cannot be changed once assigned.

my_tuple = (1, 2, 3, 4)
print(my_tuple[2])

Output:

3

This prints the third element (index 2) of the tuple, which is 3.

Common Operations on Lists and Tuples

  • Concatenation using +
  • Repetition using *
  • Membership testing using in
  • Length using len()
list1 = [1, 2]
list2 = [3, 4]
print(list1 + list2)      # Concatenation
print(list1 * 2)          # Repetition
print(3 in list2)         # Membership
print(len(list1))         # Length

Output:

[1, 2, 3, 4]
[1, 2, 1, 2]
True
2

Practice Problem

Analyze the output of the following code snippet:

tuple1 = (5, 10, 15)
list1 = [20, 25, 30]

# Convert tuple to list and append an element
temp_list = list(tuple1)
temp_list.append(20)

print(temp_list)

Solution to Practice Problem

The output will be:

[5, 10, 15, 20]

Explanation: The tuple tuple1 is converted to a list named temp_list. Then 20 is appended to this list. The original tuple remains unchanged.

Conclusion

Both lists and tuples are versatile Python data structures useful in different contexts. Lists offer flexibility with mutability, while tuples provide a fixed collection of items, which can be useful for ensuring data integrity. Practice using these types to understand their differences and use cases better.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat