Javatpoint Logo
Javatpoint Logo

Contains in Python

In 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.

Lists

Lists 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.

Tuples

Tuples are similar to lists, but they are immutable, meaning they cannot be changed after creation. Tuples are created using parentheses `( )`.

Sets

Sets are unordered collections of unique items. They are useful for storing distinct values without duplicates. Sets are created using curly braces `{ }`.

Dictionaries

Dictionaries 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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA