DEV Community

Cover image for Learn Python Lists With Definition & Code
Kola Harshita shree
Kola Harshita shree

Posted on

2

Learn Python Lists With Definition & Code

Today I learned about list methods in Python! 🐍
Here’s a quick summary of some important methods and how they work:

Image description

🌟 Key Takeaway:
Python lists are very powerful and learning these methods makes handling data so much easier!

1."Did i miss any method?"
2."How do you use these in your daily projects?"
"Feel free to share your thoughts or additional methods in the comments below. Let's learn together!""

Top comments (2)

Collapse
 
csm18 profile image
csm • Edited

As a beginner when we start using lists for the first time, one of the problems we face is with indexing a list.
Like, for example:
-> we have a list
-> we have a while loop
-> inside that loop: we do some operations on the list using the above methods.
-> like we remove some elements in the middle.
-> then we think the length and indexes of the list are same as before.
-> we try to access the index of a deleted element
-> boom! we mess up!
-> or the loop depends on the list's length and we changed the length.
These are some errors I feel are important to come across earlier as a beginner!

Collapse
 
kolaharshita profile image
Kola Harshita shree

You're absolutely right — this is a super common issue for beginners (and even experienced devs sometimes!). When you modify a list while looping over it, the indexes shift, and it can really mess things up.
Here are a few ways to avoid those problems:

below are the code

✅ 1: For loop using a copy of the list

my_list = [1, 2, 3, 4, 5] # CREATING LIST
for item in my_list[:]: # Start a for loop over a COPY of the list (not the original list)
if item == 3: # If the current item is 3
my_list.remove(item) # Remove 3 from the original list
print(my_list) # Print the list after removing 3

2: While loop with manual index control

my_list = [1, 2, 3, 4, 5] # CREATING LIST
i = 0 # Set the starting index to 0 (first element)
while i < len(my_list): # Loop as long as 'i' is smaller than the length of the list
if my_list[i] == 3: # If the item at index 'i' is 3
my_list.pop(i) # Remove the item at index 'i', Don't move to the next index because the list has shifted
else:
i += 1 # If no item was removed, move to the next index, INCREMENT i here
print(my_list) # Print the list after removing 3

⚠️ Tip to Remember:

  1. If you remove elements, indexes shift!
  2. for loops don’t automatically adapt to length changes.
  3. When in doubt, iterate over a copy, or build a new list instead.

''I hope this helps you!
If you want the code as a screenshot, I can send that to you too''

Image of Quadratic

Python + AI + Spreadsheet

Chat with your data and get insights in seconds with the all-in-one spreadsheet that connects to your data, supports code natively, and has built-in AI.

Try Quadratic free