Coding / Programming Videos

Post your favorite coding videos and share them with others!

Python for Beginners – Dhairya Kumar – Medium

Source link

Lists —

List is another data structure which is widely used in Python.It is mutable i.e we can change value of the elements after declaring them.

We can easily append 2 lists together by using the extend function.

friends = ["abc", "def", "xyz", "pqr", "mno","def"]
num = [4, 8, 12, 16, 20]
friends.extend(num)
print(friends)
#OUTPUT 
['abc', 'def', 'xyz', 'pqr', 'mno', 'def', 4, 8, 12, 16, 20]

Another cool function is zip() which allows us to join the values of the 2 or more lists.

name = ["abc", "def", "xyz", "pqr"]
roll_num = [4, 8, 12, 16]
mapped = zip(name, roll_num)
print(set(mapped))
#OUTPUT 
{('abc', 4), ('def', 8), ('pqr', 16), ('xyz', 12)}

There are various other functions which we can use on a list.

friends = ["abc", "def", "xyz", "pqr"]
friends.append("karen")
print(friends)
#OUTPUT = ['abc', 'def', 'xyz', 'pqr', 'karen']
friends.insert(1, "Joe")
print(friends)
#OUTPUT = ['abc', 'Joe', 'def', 'xyz', 'pqr']
friends.remove("abc")
print(friends)
#OUTPUT = ['def', 'xyz', 'pqr']
friends.pop()
print(friends
#OUTPUT = ['abc', 'def', 'xyz']
print(friends.count("def"))
#OUTPUT = 1
  • Here the append() function will always append the values to the end of the list.
  • If we want to insert a value at a particular location then we can use the insert() function.
  • remove() is used to remove a particualr value.
  • pop() will always delete the last element.
  • count() will return the occurences of a particular element.

We can also use functions like sort(), reverse() and copy() with lists.

friends = ["abc", "def", "pqr", "xyz"]
friends.sort()
print(friends)
#OUTPUT
['abc', 'def', 'pqr', 'xyz']
friends.reverse()
print(friends)
#OUTPUT
['xyz', 'pqr', 'def', 'abc']
friends2 = friends.copy()
print(friends2)
#OUTPUT
['abc', 'def', 'pqr', 'xyz']

Source link

Bookmark(0)
 

Leave a Reply

Please Login to comment
  Subscribe  
Notify of
Translate »