Day 6: Python Syntax: Basic Concepts — List Operation in detail

Day 6: Python Syntax: Basic Concepts — List Operation in detail

Python in 30 Days: A Practical and Theoretical Approach for Beginner.

A list is one of the most commonly used data structures in Python.

image 40 Simply Creative Minds

List Operations:

Concatenation:

You can concatenate two lists using the + operator.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # Output: [1, 2, 3, 4, 5, 6]

Repetition:

You can repeat a list using the * operator.

repeated_list = [1, 2, 3] * 2
print(repeated_list)  
# Output: [1, 2, 3, 1, 2, 3]

List comprehension:

A concise way to create lists.

squares = [x ** 2 for x in range(5)]
print(squares)  
# Output: [0, 1, 4, 9, 16]

Nested Lists:

Lists can contain other lists as elements.

nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list[0])  
# Output: [1, 2]
print(nested_list[0][1]) 
 # Output: 2

Common List Methods:

  • append(): Adds an item to the end of the list.
  • insert(): Adds an item at a specified index.
  • remove(): Removes the first occurrence of an item.
  • pop(): Removes and returns an item at a given index (default is the last item).
  • sort(): Sorts the list in place (alphabetically or numerically).
  • reverse(): Reverses the list.
  • clear(): Removes all items from the list.

Happy Coding and Stay Tuned 🙂

Kind is always cool !!!

Share knowledge to gain knowledge !!!!

Be kind and treat people with respect !!!

If you find my blog helpful, then please subscribe, claps and follow to support 🙂

image 35 Simply Creative Minds

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *