Contains in PythonIn Python, a `container` is an object that holds other objects. Containers provide a way to organize and manage collections of data. Python provides several built-in container types, including `lists`, `tuples`, `sets`, and `dictionaries`. Each type has its own characteristics and use cases. ListsLists are ordered collections of items. They are mutable, which means you can change the items in a list after it has been created. Lists are created using square brackets `[ ]` and can contain items of different data types. TuplesTuples are similar to lists, but they are immutable, meaning they cannot be changed after creation. Tuples are created using parentheses `( )`. SetsSets are unordered collections of unique items. They are useful for storing distinct values without duplicates. Sets are created using curly braces `{ }`. DictionariesDictionaries are collections of key-value pairs. Each key is associated with a value, similar to a real-world dictionary where words (keys) are associated with definitions (values). Dictionaries are created using curly braces `{ }` and colons `:` to separate keys and values. Container Operations:Accessing Items:Items in a container can be accessed using indexing (for lists and tuples) or keys (for dictionaries). Example 1: Output: 1 Example 2: Output: Alice Adding and Removing Items:Containers can be modified by adding or removing items. Example 1: Output: [1, 2, 3, 4] Example 2: Output: {"name": "Alice", "age": 30} Iterating Over Containers:You can iterate over the items in a container using loops. Example: Output: 1 2 3 name: Alice age: 30 Explanation: The first loop iterates over the my_list list and prints each item (1, 2, 3) on a new line.The second loop iterates over the key-value pairs in the my_dict dictionary and prints each pair in the format key: value, where key is the key from the dictionary (name, age) and value is the corresponding value (Alice, 30). These are some of the basics of containers in Python. Containers play a crucial role in organizing and managing data in Python programs. Next TopicLabel Encoding in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India